1

我正在尝试获取Twitter 上当前趋势列表的第一项。我创建了一些代码,但它返回一个空列表。我想知道我哪里出错了,我对 JSON 很陌生,所以对任何代码建议的解释将不胜感激 - 非常感谢。

MainActivity.java

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

private static String url = "https://api.twitter.com/1/trends/1.json";

private static final String TAG_NAME = "name";

ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new ProgressTask(MainActivity.this).execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class ProgressTask extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog dialog;

    public ProgressTask(Activity activity) {

        Log.i("1", "Called");
        context = activity;
        dialog = new ProgressDialog(context);
    }

    /** progress dialog to show user that the backup is processing. */

    /** application context. */
    private Context context;

    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

    @Override
    protected void onPostExecute(final Boolean success) {
          if (dialog.isShowing()) {
                dialog.dismiss();
               }
               Toast.makeText(context, jsonlist.get(0).toString(), Toast.LENGTH_LONG).show();

    }

    protected Boolean doInBackground(final String... args) {

        TrendsJSONParser jParser = new TrendsJSONParser();

        // getting JSON string from URL
        JSONArray json = jParser.getJSONFromUrl(url);

        for (int i = 0; i < json.length(); i++) {

            try {
                JSONObject c = json.getJSONObject(i);
                String trendName = c.getString(TAG_NAME);

                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_NAME, trendName);

                jsonlist.add(map);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return null;

    }

}

   }

这是我的 TrendsJSONParser.java 源代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

public class TrendsJSONParser {

 static InputStream is = null;
 static JSONArray jarray = null;
 static String json = "";

 // constructor
 public TrendsJSONParser() {

 }

 public JSONArray getJSONFromUrl(String url) {

     StringBuilder builder = new StringBuilder();
      HttpClient client = new DefaultHttpClient();
      HttpGet httpGet = new HttpGet(url);
      try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
          HttpEntity entity = response.getEntity();
          InputStream content = entity.getContent();
          BufferedReader reader = new BufferedReader(new InputStreamReader(content));
          String line;
          while ((line = reader.readLine()) != null) {
            builder.append(line);
          }
        } else {
          Log.e("==>", "Failed to download file");
        }
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

  // try parse the string to a JSON object
  try {
   jarray = new JSONArray( builder.toString());
  } catch (JSONException e) {
   Log.e("JSON Parser", "Error parsing data " + e.toString());
  }

  // return JSON String
  return jarray;

 }
}
4

0 回答 0