Integrating Twitter API in Android App

In this tutorial, we will integrate the Twitter Log-in API into an Android app. For integrating Twitter API in the Android app, it requires the app Consumer Key (API Key) and Consumer Secret (API Secret). It can be generated from https://apps.twitter.com/.

Combining the Twitter API in Android app helps users for log-in using the Twitter account, share tweets, etc.

Steps to generate Twitter API Key and API Secret

1. Log-in at https://apps.twitter.com/ with your Twitter account and click on 'Create New App'.


android Twitter Integrating

2. Fill all the required detail in new open form and click on 'Create your Twitter Application'.


android Twitter Integrating

3. Select the application permission mode for our app. Here we select Read, Write and Access direct messages and click 'Update Settings'.


android Twitter Integrating

4. Now, open the 'Settings' tab and fill all the required details and click 'Update Settings'.


android Twitter Integrating

5. Now again, open Permissions tab and enable 'Request email from users' and click again 'Update settings'.


android Twitter Integrating

6. Now, open 'Key and Access Tokens' tab, we will find our app 'Consumer Key' and 'Consumer Secrets'.


android Twitter Integrating

Example to Integrate Twitter Login in Android app

Let's create an example of integrating login through a Twitter account in an Android app.

Create an Android app and add the following twitter dependencies in 'build.gradel' (Module) file.

Make sure that "jcenter()" is present in 'build.gradel' (Project) file.

strings.xml

Place the 'Consumer Key' and 'Consumer Secret' of our app generated by Twitter in 'strings.xml' file.

activity_main.xml

Add the Twitter login button provided by Twitter API in 'activity_main.xml' file.

MainActivity.java

Add the following code in 'MainActivity.java' file. We should place 'Twitter.initialize(this)' code before 'setContentView(R.layout.activity_main)'. If we place 'Twitter.initialize(this)' after the 'setContentView(R.layout.activity_main)' then our Twitter button will disable.

Now we create another Activity for redirecting user after successful login.

activity_home.xml

HomeActivity.java

In this class, we will display the user name received from 'MainActivity.java' file in TextView.

Output:

android Twitter Integrating android Twitter Integrating
android Twitter Integrating android Twitter Integrating




Latest Courses