0

I am using Twitter4j to fetch the followers of a given user. At some point I always hit the rate limit. I am happy for the program to sleep for 15 minutes to over come this. However when it wakes, I get an error.

See the following code:

protected IDs fetchAndStoreFollowers(TwitterUser user) {
    Twitter twitter = this.getTwitterApi();
    long cursor = -1;
    IDs ids = null;
    do {
        try {
            ids = twitter.getFollowersIDs(user.getId(), cursor);
            System.out.println("Got a followers batch");
            cursor = ids.getNextCursor();
            this.storeFollowers(user, ids);
            System.out.println("Saved!");
        } catch (TwitterException e) {
            System.out.println("Oh no! Rate limit exceeded... going to sleep.");
            handleTwitterException(e);
            System.out.println("Waking up!");
        }
    } while (ids.hasNext());
    return ids;
}

After waking up from the sleep the program throws a NullPointerException on this line:

} while (ids.hasNext());

Can anybody spot why?

MWiesner
  • 8,868
  • 11
  • 36
  • 70
calmcalmuncle
  • 143
  • 1
  • 2
  • 16

1 Answers1

2

The cause of the encountered error is reproducible and quite logic.

First, you initialize your ids to null.

In case a RateLimitException (TwitterException) occurs, no actual value is ever set to the variable ids in the line with:

ids = twitter.getFollowersIDs(user.getId(), cursor);

The code in the catch-Block is then executed - while ids is still pointing to null. After this is processed (and you see output on your console...), the line:

while (ids.hasNext());

produces the NullPointerException.

Solution

Change the while-condition as follows:

while (ids == null || (id!=null && ids.hasNext()));

Be aware that the value in cursor might not have been or has to be changed accordingly, in case of an error situation.

Hope this helps.

MWiesner
  • 8,868
  • 11
  • 36
  • 70