只能迭代数组或 java.lang.Iterable 的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9839961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can only iterate over an array or an instance of java.lang.Iterable
提问by BoneStarr
Hi I keep getting this error, I'm trying to get tweets from twitter via JSON and cant seem to get rid of this on the "arr". Would I have to do a different for loop? I did try this but it keeps returning the same error.
嗨,我不断收到此错误,我正在尝试通过 JSON 从 twitter 获取推文,但似乎无法在“arr”上摆脱此错误。我必须做一个不同的 for 循环吗?我确实尝试过,但它一直返回相同的错误。
public ArrayList<Tweet> getTweets(String searchTerm, int page) {
String searchUrl =
"http://search.twitter.com/search.json?q=@"
+ searchTerm + "&rpp=100&page=" + page;
ArrayList<Tweet> tweets =
new ArrayList<Tweet>();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler =
new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch(Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject = null;
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(responseBody);
jsonObject=(JSONObject)obj;
}catch(Exception ex){
Log.v("TEST","Exception: " + ex.getMessage());
}
JSONArray<Object> arr = null;
try {
Object j = jsonObject.get("results");
arr = (JSONArray)j;
} catch(Exception ex){
Log.v("TEST","Exception: " + ex.getMessage());
}
for(Object t : arr) {
Tweet tweet = new Tweet(
((JSONObject)t).get("from_user").toString(),
((JSONObject)t).get("text").toString(),
((JSONObject)t).get("profile_image_url").toString()
);
tweets.add(tweet);
}
return tweets;
}
Please help!!
请帮忙!!
采纳答案by Sebastien
As the exception says, you can only iterate with the for each loop on instances of java.lang.Iterable
. JSONArray
is not one of them.
正如例外所说,您只能在 的实例上使用 for each 循环进行迭代java.lang.Iterable
。JSONArray
不是其中之一。
Use the "classic" for loop :
使用“经典” for 循环:
for(int i = 0; i < arr.length(); i++) {
JSONObject t = (JSONObject) arr.get(i);
Tweet tweet = new Tweet(
t.get("from_user").toString(),
t.get("text").toString(),
t.get("profile_image_url").toString()
);
tweets.add(tweet);
}