sf9251
sf9251

Reputation: 288

How to get fixed number of tweets using twitter4j

I am using Twitter4j to build a client to fetch tweets for the input search term. I am also trying to provide the facility to the user to enter the number of tweets he wants in the result.

I know that we can set the number of tweets to be returned per page with the Query's setCount() method:

Query q = new Query(searchTerm);   
q.setCount(maxTweets);    

But if I am giving the value 1 as maxTweets, it returns 2 tweets.

Update: After further research I observed that it is returning 1 extra tweet per search. So I am giving 1 as maxTweets value it is returning 2 tweets. If I am giving 2 as maxTweets value it is returning 3 tweets and so on.

I am not sure where I am wrong but please let me know if there is a way by which I can get the fixed number of tweets using twitter4j.

Any guidance will be helpful.

Upvotes: 0

Views: 1529

Answers (1)

user3764893
user3764893

Reputation: 707

When you write

Query q = new Query(searchTerm);   

Think of it as one tabled page which contains an amount of result matching your query. But there might be more multiple pages.

When you set

q.setCount(maxTweets);

it will bring you maxTweets amount of tweets per page. In your case, 2, because there were two pages matching your query and you selected one tweet per page.

What you can do, try to handle it with a do - while loop.

        Query q = new Query(searchTerm);
        QueryResult result;
        int tempUSerInput = 0; //keep a temp value
        boolean flag = false;

        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets(); 

            tempUSerInput = tempUSerInput + tweets.size();

            if(tempUSerInput >= realyourUserInput) // you have already matched the number
                flag = true;                //set the flag 

        } 

        while ((query = result.nextQuery()) != null && !flag);


        // Here Take only realyourUserInput number
        // as you might have taken more than required

        List<Status> finaltweets = new ArrayList();

        for(int i=0; i<realyourUserInput; i++)
            finaltweets.add( tweets.get(i) );   //add them to your final list

Upvotes: 1

Related Questions