android java:foreach通过json数组返回值?

时间:2012-02-26 18:26:47

标签: java android arrays json for-loop

我在java代码中为每个循环执行操作时遇到问题。我可以获得单个json结果,但是如何在此代码中为每个循环使用a?

有人可以帮助我吗?

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循环。但是,如果我将其用于循环播放,而不是i中的JSONObject value = timeline.getJSONObject(i)并且具有01等数字值,那么它会输出。

另外,我相信类Read,return json.getString(params[0])也需要在循环中工作吗?我只是JAVA的新手,我正在努力学习一切。

提前谢谢!

1 个答案:

答案 0 :(得分: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;
    }