2012-02-26 68 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; 
    }