1

I am able to get the live twitter stream using the twitter streaming api like below

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey("xxxx");
    cb.setOAuthConsumerSecret("xxxx");
    cb.setOAuthAccessToken("xxxx");
    cb.setOAuthAccessTokenSecret("xx");
    int count = 0;
    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    StatusListener listener = new StatusListener() {


        public void onStatus(Status status) {

            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
           // count++;
        }


        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        public void onException(Exception ex) {
            ex.printStackTrace();
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }
    };

    FilterQuery fq = new FilterQuery();
    String keywords[] = {"samsung"};
    String lang[] = {"en"};
    fq.track(keywords);
    fq.language(lang);
    twitterStream.addListener(listener);
    twitterStream.filter(fq);   

How do I restrict the number of tweets? The above program is running indefinitely. How do I stop the program after getting the required number of tweets?

yAsH
  • 3,367
  • 8
  • 36
  • 67
  • possible duplicate of [stop the Twitter stream and return List of status with twitter4j](http://stackoverflow.com/questions/18016532/stop-the-twitter-stream-and-return-list-of-status-with-twitter4j) – Jonathan Jun 04 '14 at 08:33

1 Answers1

0

Limit storing your tweets in for instance LinkedBlockingQueue

private LinkedBlockingQueue<Status> tweets = new LinkedBlockingQueue<>(10000);

StatusListener listener = new StatusListener() {

@Override
public void onStatus(Status status) {
    tweets.add(status);
}

You can later retrive it in foreach loop using Status message = obrada.poll(); .... Or just create counter and ask for size of your regular ArrayList --

if (tweets.size() >= 1000) twitterStream.shutdown(); twitterStream.cleanUp();

Orbita
  • 169
  • 2
  • 9