I'm trying to use an arraylist of Tweets that has been populated inside a callback but I can't figure out how to return the built list. Whenever I try to use the built list it's empty.
I got some code from this post
public ArrayList<Tweet> tweetList() {
final ArrayList<Tweet> tweets = new ArrayList<>();
final UserTimeline userTimeline = new UserTimeline.Builder()
.screenName("xxxxxxxx")
.build();
userTimeline.next(null, new Callback<TimelineResult<Tweet>>() {
@Override
public void success(Result<TimelineResult<Tweet>> result) {
for(Tweet tweet : result.data.items){
tweets.add(tweet);
}
Log.d("Finished Tweet List", String.valueOf(tweets));
// when this is printed I can see the ArrayList and all tweets are there
}
@Override
public void failure(TwitterException exception) {
exception.printStackTrace();
}
});
Log.d("Tweet list returned", String.valueOf(tweets));
// the value of tweets is empty here for some reason
return tweets;
}
Instead of returning the empty ArrayList
of Tweet
s, you can modify your method so another ArrayList
of Tweet
s is updated when the response from the Callback
succeeds.
So I suggest modifying your method as follows:
private ArrayList<Tweet> tweetList = new ArrayList<>();
public void tweetList() {
final ArrayList<Tweet> tweets = new ArrayList<>();
final UserTimeline userTimeline = new UserTimeline.Builder()
.screenName("xxxxxxxx")
.build();
userTimeline.next(null, new Callback<TimelineResult<Tweet>>() {
@Override
public void success(Result<TimelineResult<Tweet>> result) {
for(Tweet tweet : result.data.items){
tweets.add(tweet);
}
this.tweetList = tweets;
// execute the next sequence of instructions in your program here
// and make use of tweetList instead of tweets
}
@Override
public void failure(TwitterException exception) {
exception.printStackTrace();
}
});
}