我正在尝试制作一个使用JSON
解析来自Twitter的数据并获取实时Twitter提要的应用程序,我能够成功将数据记录到logcat中,但是不知何故我无法在ListView
中显示它们,最后的新闻提要显示在ListView
中,但其余的提要都消失了。我在使用Arraylist
之前将它们添加到ArrayAdapter
中。我的代码出了什么问题?我是正确解析了JSONArray
和JSONObject
还是缺少任何转换?
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();
}
}
最佳答案
只需在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);