Searching tweets on Twitter using Twitter4j

25 / Sep / 2012 by Vishal Sahu 0 comments

Hi,
In the previous blog we saw how to fetch tweets posted by a particular user using the Twitter4j,a java wrapper library available for Twitter API calls.


In the same grails project, i had the requirement to display the based on some search criteria or words. Twitter4j library provides a cool way to search tweets over twitter with its Query class. It helped me a lot to make quick search of tweets on twitter.



Twitter search API is open for all and we need not to have any user authentication required to achieve it. We just need to have and registered app on twitter and thats it.


Code to search Tweets:-

[java]

String queryString=’Grails’ // some word which you want to search on twitter
Integer numberOfTweets = 20
Twitter twitter = new TwitterFactory().getInstance();
Query query = new Query(queryString);
query.setRpp(numberOfTweets)
query.setPage(1)
QueryResult result = twitter.search(query);
List tweets = result.getTweets();
tweets.each {tweet ->
println "ID : ${tweet.id}"
println "User : ${tweet.user.screenName}"
println "Tweet : ${tweet.text}"
}
[/java]

This code will fetch the latest 20 tweets which fits the searched criteria.

Hope this helps.


FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *