Twitter is an online news and Social Networking Service where users can post and read messages from other users. Twitter messages, tweets as they are called have a limit of 140 characters. Twitter has already become one of the most used messaging services because it caters to both official and unofficial communication.
In this blog, we will be discussing how can we integrate Android Apps with Twitter. We will be logging into our app using twitter and fetching the email id of the user in the twitter account.We will also be discussing how to make the app fetch tweets of a particular twitter account. Steps to develop this can be summarized below -
We will be using Twitter Developer Kit here which is provided by Twitter Devlopers website.
Now, let us begin the development...
Run ‘Sync Gradle’ after you add the dependencies.
Twitter login Button is available from the Twitter Dependency that we added earlier. We add another button to show the tweets from a particular account which we will code later.
a) We initialize Twitter inside onCreate method before calling setContentView(R.layout.activity_main). If initialization is done after calling setContentView - you will find that the twitter login button is devoid of its blue color. While configuring Twitter for this app , we also provide the keys and access token which we got from the twitter website earlier.
b) We set a callback on the login button to handle a click by the user on the ‘Login by Twitter Button’. Inside the callback we create a sessions and can use the token/secret code if required.In this case we are showing it in the Toast Message.
c) Use a TwitterAuthClient to fetch email of the user. Using TwitterAuthClient we are trying to fetch email id of the user . An email id will be aprovided only if the user registered with an email id in their twitter account. Also, you need to have given a permission in the apps.twitter link which we dealt with earlier. Here we display the email id using a Toast message.
d) Use Twitter’s Composer Activity to create a tweet dialog with a Tweet button.
We have another button in the MainActivity’s layout which can be clicked to see a particular account’s tweets in a list. We do this in the ShowTweetActivity.class
a) This activity extends a ListActivity and uses a TwitterListAdapter to set the data on the list. Below is the layout that we use for this activity.
b) Make sure the id that you provide to the list view is not the general id using @+id. You need to use the id from the Android SDK.
Layout for ShowTweetActivity.class
The user can now click on Tweet Button and post this tweet on their twitter timeline.