android java: foreach через массив json, возвращающий значения? - PullRequest
1 голос
/ 26 февраля 2012

У меня проблемы с выполнением каждого цикла в моем Java-коде. Я могу получить отдельные результаты 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. но если я возьму это для loop out, и вместо того, чтобы иметь i in JSONObject value = timeline.getJSONObject(i) и иметь числовое значение, такое как 0 или 1, тогда оно выдаст.

Кроме того, я полагаю, что в классе Read return json.getString(params[0]) также должен работать в цикле for? Я просто новичок в JAVA и пытаюсь научиться всему самостоятельно.

Заранее спасибо!

1 Ответ

0 голосов
/ 28 февраля 2012
    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;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...