Twitter tutorial covering hashtags, reply & favorite/un-favorite using twitter4j

This article is in continuation to our previous article which demonstrated user how to authenticate on twitter and post tweet with/without image using twitter4j. This article will help you understand on how to fetch tweets using hashtags and other twitter actions like tweet, re-tweet etc . So lets begin tweeting…I mean the tutorial 🙂 #letsBegin In social media everyone is aware of #hashtags, here we will explain how to fetch tweets for a particular hash tags. we are using “Query” class to fetch tweets.


Query query = new Query(“#android”);

Here, above code snippet is to fetch tweets containing “#android” hashtag. Multiple hashtags You can also fetch tweets for more than one hashtags, say you want to fetch tweets containing hashtag #code or #android,  you need to include both tags with keyword “OR”. for eg:  “#code OR #android” ,  “#code AND #android” Now lets see the above code in action.


Query query = new Query(hashtag);

query.count(10); //  Query will return only 10 tweets per request.

QueryResult queryResultObject = twitter.search(query);

List<twitter4j.Status> qrTweets = queryResultObject.getTweets();

queryResultObject.getTweets()  will return list of twitter4j.Status, which contains tweet data  like retweet count as well as tweet’s owner info. for eg: user screen name, profile image etc Here is code snippet to fetch tweet related data from status model.


status.getUser().getName(); // to get user name

status.getId();// to get tweet id

status.getUser().getScreenName(); // to get user screen name/ user handler

status.getText();// tweet

status.getFavoriteCount(); // favorite count

status.getRetweetCount();// retweet count

PAGINATION setMaxId(int) is useful to fetch next set of tweets . this method will  return tweets with status ids less than the given id.


query.setMaxId(lastSeenId);

TWITTER ACTIONS To perform actions like reply retweet you need to authenticate user on twitter. You can find a tutorial on how to authenticate user on twitter using twitter4j here 1] Favorite To perform fav action on any tweet  you  can use createFavorite() method with tweet id.


twitterInstance.createFavorite(mTweetId)

2] Re-tweet To re-tweet tweet  use  retweetStatus() method with tweet id.


twitterInstance.retweetStatus(mTweetId)

3] Reply To reply on a tweet use updateStatus() method with tweet id.


Twitter twitter = TwitterHelper.getTwitterInstance(mContext);

StatusUpdate statusUpdate = new StatusUpdate(mReplyText);

statusUpdate.inReplyToStatusId(mTweetId);

twitter.updateStatus(statusUpdate);

4] Un-favorite To un-favorite  any tweet  you  can use destroyFavorite() method with tweet id


twitterInstance.destroyFavorite(mTweetId)

Just follow the sample, and you’re ready to tweet. Any issues feel free to contact us. You can download working project from github. Happy Coding Happy Learning 🙂

Advertisements