1

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.

 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!!

BoneStarr
  • 195
  • 1
  • 3
  • 15
  • hava a look here! [iterate over json array](http://stackoverflow.com/questions/3408985/json-array-iteration-in-android-java) – Vossi Mar 23 '12 at 13:33

2 Answers2

5

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.

Use the "classic" for loop :

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);
 }
Sebastien
  • 677
  • 4
  • 10
  • Thanks this helped me to compile the code but im getting runtime errors at these two lines now: tweets = getTweets("android", 1); & for(int i = 0; i < arr.length(); i++) { – BoneStarr Mar 23 '12 at 16:06
1

JSONArray doesn't implement Iterable. Use length and get to access the members within it (see here)

int count = arr.length();
for (int i=0;i<count;++i) {
  string s = arr.getString(i);
}
Jeff Foster
  • 43,770
  • 11
  • 86
  • 103