Search code examples
javasearchtwittertwitter4j

How to get more than 100 tweet result using twitter4j


I used the code in the first solution provided here How to retrieve more than 100 results using Twitter4j

But it just retrieves the repetition of the first 100 tweets.

I also tried to setSince and setUntil dates, but also it retrieves the repetition.

Any help please! Thanks.


Solution

  • If you want to get a continious stream of tweets based on some query filter,Implement StatusListener Class in Twitter4j. Also implement onStatus(Status status) function.Below is an example -

    import twitter4j.*;
    
    public class TwitterListener implements StatusListener {
        public void onException(Exception ex) {
            ex.printStackTrace();
        }
        public void onStatus(Status status) {
            if(status.getUser().getLang().equalsIgnoreCase("en")
                    || status.getUser().getLang().equalsIgnoreCase("en_US")) {
    
                String twitterStream = String.valueOf(status.getId())
                    + "\t" + status.getUser().getScreenName()
                    + "\t" + status.getText()
                    + "\t" + status.getCreatedAt();
    
                System.out.println(twitterStream);
            }
        }
    
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }
        public void onScrubGeo(long userId, long upToStatusId) {
        }
        public void onStallWarning(StallWarning warning) {
        }
    }
    

    Create a class to initialize and hook to Twitter Status Stream, the code would be something like below -

    ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
    twitterConfigBuilder.setOAuthConsumerKey("consumerKey");
    twitterConfigBuilder.setOAuthConsumerSecret("consumerSecret");
    twitterConfigBuilder.setOAuthAccessToken("accessToken");
    twitterConfigBuilder.setOAuthAccessTokenSecret("accessTokenSecret");
    
    TwitterListener twitterListener = new TwitterListener();
    
    TwitterStream twitterStream
            = new TwitterStreamFactory(twitterConfigBuilder.build()).getInstance();
    
    // Register your Listener
    twitterStream.addListener(twitterListener);
    
    FilterQuery query = new FilterQuery();
    ArrayList<String> trackList = new ArrayList<String>();
    // TODO, add the list of words you want to track
    query.track(trackList.toArray(new String[trackList.size()]));
    
    twitterStream.filter(query);
    

    You should now be able to get a continious stream of tweets, you can experiment more on kind of filter you want to apply.