How to get more than 20 results from a user timeline with Twitter4j?

edited October 2013 in How To...

Hello everybody,

I'm trying to make a sketch that gets the last 100 tweets from a specific user's twitter timeline. I'm using Twitter4j and the sketch works fine but I've learned that Twitter4J by default limits the results to 20. There's a lot of talk about how to get more than 20 when using search queries but I'm interested in a specific user's timeline. And I don't know how to approach this.

Thanks for looking!

Here is the sketch:

import twitter4j.conf.*;
import twitter4j.internal.async.*;
import twitter4j.internal.org.json.*;
import twitter4j.internal.logging.*;
import twitter4j.json.*;
import twitter4j.internal.util.*;
import twitter4j.management.*;
import twitter4j.auth.*;
import twitter4j.api.*;
import twitter4j.util.*;
import twitter4j.internal.http.*;
import twitter4j.*;
import twitter4j.internal.json.*;


ConfigurationBuilder cb = new ConfigurationBuilder();

cb.setOAuthConsumerKey("XXXXXX");
cb.setOAuthConsumerSecret("XXXXXX");
cb.setOAuthAccessToken("XXXXXX");
cb.setOAuthAccessTokenSecret("XXXXXX");

java.util.List statuses = null;

Twitter twitter = new TwitterFactory(cb.build()).getInstance();

String userName ="XXXXXX";
int numTweets = 100;
String[] twArray = new String[numTweets];



  try {
    statuses = twitter.getUserTimeline(userName);
  } 
  catch(TwitterException e) {
  }

  for (int i=0; i<statuses.size(); i++) {
    Status status = (Status)statuses.get(i);

    //println(status.getUser().getName() + ": " + status.getText());
    twArray[i] = status.getUser().getName() + ": " + status.getText();
    println(twArray);
  }

Answers

  • edited October 2013 Answer ✓

    hi merijn,

    it looks like getUserTimeline() also will accept a Paging object that may let you control more of how many tweets to pull down

    Example number 6 here: http://twitter4j.org/en/code-examples.html Shows how to use the Paging object: http://twitter4j.org/oldjavadocs/3.0.4-SNAPSHOT/twitter4j/Paging.html

    which I think you could use something like this:

    Paging page = new Paging (1, 50);//page number, number per page
    statuses = twitter.getUserTimeline(userName, page);
    

    then get and save those tweets, then call:

    page.setPage(2);

    and get the users timeline again, and it will get the next 50 items.

    Alternately, you could just set the second param in the Paging init to your 100 to get the first 100 tweets. Twitter may not allow that though, then a few calls with paging is the way to go.

    Hope this helps! ak

  • Thank you Akiersky, your answer was very helpful!

    It seems to be working fine with Paging(1,100);

Sign In or Register to comment.