У меня возникли проблемы с выполнением каждого цикла в моем 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. но если я возьму это для цикла, и вместо того, чтобы иметь это значение i
в JSONObject value = timeline.getJSONObject(i)
и иметь числовое значение, например 0
или 1
, то оно выводит.
Кроме того, я верю в класс Read, return json.getString(params[0])
также нужно будет обрабатывать как для цикла? Я просто совершенно новый для JAVA, и я стараюсь все учиться самостоятельно.
Заранее спасибо!
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;
}