2012-02-26 65 views
1

我在为我的java代码中的每个循环做一个麻烦。我可以得到单个json结果,但是如何在此代码中为每个循环使用a?android java:foreach通过json数组返回值?

有人可以帮助我吗?

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; 
    } 

我得到JSONObject的feedTimeline错误...如果我有for循环。但是如果我将其用于循环输出,而不是在JSONObject value = timeline.getJSONObject(i)中具有i并且具有01等数值,则它会输出。

此外,我相信在类读,return json.getString(params[0])也需要工作在循环?我对JAVA真的很陌生,我试图自己学习所有东西。

预先感谢您!

+0

字符串值= timeline.getJSONString(“你的字符串名”) – 2012-02-26 18:29:15

+0

您好,我很抱歉,我还是有点新到Java,你能向我解释你是什么意思? – hellomello 2012-02-26 18:38:03

+0

你可以给我你的网址吗? – 2012-02-26 18:39:50

回答

0
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);  
     } 
// changed the position of return statement. This should work now. 
      return null; 
    }