I am trying to make an app that parses data from Twitter using JSON and get the live twitter feed, I was successfully able to log the data into the logcat, but somehow I am unable to display the same in the ListView, the last news feed is showing up in the ListView but the rest of feeds are gone. I add them in an Arraylist before using an ArrayAdapter to do so.What is wrong with my code, am I parsing the JSONArray and JSONObject correctly or is there any conversion that I am missing?
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();
}
}
Just initializing the string array before the for loop and set adapter after completion of for loop..
Try this, replace in your code.