I'm having trouble doing a for each loop in my java code. I can get single json results, but how do I use a for each loop in this code?
Can someone help me?
public JSONObject feedTimeline(String username) throws ClientProtocolException, IOException, JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity e = response.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
for (int i = 0; i < timeline.length(); i++) {
JSONObject value= timeline.getJSONObject(i); //no error if this i is 0 and without for each loop
return value; //getting errors because of this return tweets
}
}else{
Toast.makeText(Feed.this,"error",Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = feedTimeline("name");
return json.getString(params[0]); //this would need to change I assume?
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
I'm getting an error for JSONObject feedTimeline... if I have the for loop. but if I take that for loop out, and instead of having that i
in JSONObject value = timeline.getJSONObject(i)
and having a numberical value like 0
or 1
, then it does output.
Also, I believe in class Read, return json.getString(params[0])
would also need to be worked in as for loop? I'm just really new to JAVA and I'm trying to learn everything on my own.
Thank you in advance!
public static String URL = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";
– andrewliu Feb 26 '12 at 18:48