无法在Android ListView中显示Twitter Feed

时间:2011-11-19 09:55:45

标签: android android-listview

我正在尝试创建一个使用JSON从Twitter解析数据的应用程序并获取实时推特,我已成功将数据记录到logcat中,但不知怎的,我无法显示相同的内容ListView,最后一条新闻Feed显示在ListView,但其余的Feed已消失。我在使用Arraylist之前将其添加到ArrayAdapter中。我的代码出了什么问题,我是正确解析JSONArrayJSONObject还是有任何转换我失踪了?

public class readingtwitterfeedsActivity extends ListActivity {

    @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   // setContentView(R.layout.main);
    String readTwitterFeed = readTwitterFeed();
    try {
        JSONArray jsonArray = new JSONArray(readTwitterFeed);
        Log.i(readingtwitterfeedsActivity.class.getName(),
                "Number of entries " + jsonArray.length());
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Log.i(readingtwitterfeedsActivity.class.getName(),   jsonObject.getString("text"));
            List<String> al=new ArrayList<String>();
            al.add(jsonArray.getJSONObject(i).getString("text"));
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, al);
            setListAdapter(adapter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

  public String readTwitterFeed() {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(
            "http://twitter.com/statuses/user_timeline/bbcnews.json");
    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(readingtwitterfeedsActivity.class.toString(), "Failed to download file");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return builder.toString();
}
}

1 个答案:

答案 0 :(得分:2)

只需在for循环之前初始化字符串数组,并在完成for循环后设置适配器。

试试这个,替换你的代码。

List<String> al=new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Log.i(readingtwitterfeedsActivity.class.getName(),   jsonObject.getString("text"));

            al.add(jsonArray.getJSONObject(i).getString("text"));

        }
 ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, al);
            setListAdapter(adapter);