Hello to all, today we are going to learn how to implement Twitter Integration in our Android app and let user do Sign In in single click.
Twitter Integration lets users sign in to your Android app with their existing Twitter account and get their profile information like name, email, profile pic and other details.
This tutorial includes:
1. Login using TwitterLoginButton.
2. Login using Custom button.
3. Fetch user Email.
4. Fetch user Profile picture.
So lets start integrating Twitter in our Android app. So first of all we need to create an App on Twitter.
1. To create an App got to this link and follow the step by step process.
Please check my video first part to see how to create an App on Twitter.
2. After creating app you will get two things from it i.e API Key and API Secret. Copy both the API Key and Secret and place in Android project inside string.xml.
Now after creating an app and getting API Key and Secret move to Android Studio and follow the below steps:
1. First of all open the build.gradle file and add the below dependency to it to use Twitter APIs in our app.
1 2 3 4 5 6 7 8 9 10 11 |
//Check this link for more Twitter APIs : https://dev.twitter.com/twitterkit/android/installation // Include all the Twitter APIs //compile 'com.twitter.sdk.android:twitter:3.1.1' //include only the necessary dependencies to avoid the Android dex limit compile 'com.twitter.sdk.android:twitter-core:3.1.1' compile 'com.twitter.sdk.android:tweet-ui:3.1.1' //dependency to load image url over image view implementation 'com.squareup.picasso:picasso:2.5.2' |
Read more about Twitter APIs here.
2. Now create a xml layout naming activity_main.xml and add the below code to it. In this class i have taken 3 Button : 1 for Default Twitter Login, 2 for Custom Login Button and 3 to Fetch user profile image as Twitter won’t give profile image in default login process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp" tools:context="com.twitter_auth_demo.MainActivity"> <!-- default twitter login button --> <com.twitter.sdk.android.core.identity.TwitterLoginButton android:id="@+id/default_twitter_login_button" android:layout_width="match_parent" android:layout_height="wrap_content" /> <!-- custom login button --> <Button android:id="@+id/custom_twitter_login_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:onClick="customLoginTwitter" android:text="@string/custom_log_in_with_twitter" /> <!-- fetch profile image button --> <Button android:id="@+id/profile_image_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:onClick="fetchTwitterImage" android:text="@string/get_profile_image" /> <!-- image view to show user profile image --> <ImageView android:id="@+id/user_profile_image_view" android:layout_width="120dp" android:layout_height="120dp" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" /> <!-- text view to show user details --> <TextView android:id="@+id/user_details_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:textColor="@color/colorPrimary" android:textSize="15sp" /> </LinearLayout> |
3. Once you’ve included the Twitter Kit dependencies you must initialise Twitter Kit. For this create custom Application class you can initialize Twitter Kit in the onCreate() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.twitter_auth_demo; import android.app.Application; import android.util.Log; import com.twitter.sdk.android.core.DefaultLogger; import com.twitter.sdk.android.core.Twitter; import com.twitter.sdk.android.core.TwitterAuthConfig; import com.twitter.sdk.android.core.TwitterConfig; /** * Created by sonu on 15/01/18. */ public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); TwitterConfig config = new TwitterConfig.Builder(this) .logger(new DefaultLogger(Log.DEBUG))//enable logging when app is in debug mode .twitterAuthConfig(new TwitterAuthConfig(getResources().getString(R.string.com_twitter_sdk_android_CONSUMER_KEY), getResources().getString(R.string.com_twitter_sdk_android_CONSUMER_SECRET)))//pass the created app Consumer KEY and Secret also called API Key and Secret .debug(true)//enable debug mode .build(); //finally initialize twitter with created configs Twitter.initialize(config); } } |
After creating class you have to declare Application class in manifest file inside application tag like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> |
4. Next, add your API key and secret which you got after creating app on Twitter to to your application strings.xml resources.
1 2 |
<string name="com.twitter.sdk.android.CONSUMER_KEY">your_consumer_key</string> <string name="com.twitter.sdk.android.CONSUMER_SECRET">your_consumer_secret</string> |
There are some extra strings that i am using in my app if you want to add them too you can:
1 2 3 4 5 6 7 8 |
<resources> <string name="app_name">Twitter Auth Demo</string> <string name="com.twitter.sdk.android.CONSUMER_KEY">your_consumer_key</string> <string name="com.twitter.sdk.android.CONSUMER_SECRET">your_consumer_secret</string> <string name="custom_log_in_with_twitter">Custom Log in with Twitter</string> <string name="get_profile_image">Fetch Profile Image</string> </resources> |
1 2 3 4 |
<com.twitter.sdk.android.core.identity.TwitterLoginButton android:id="@+id/login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" /> |
6. After adding TwitterLoginButton to xml layout use the attach the below code to your Activity or Fragment.
1 2 3 4 5 6 7 8 9 10 11 12 |
twitterLoginButton = (TwitterLoginButton) findViewById(R.id.default_twitter_login_button); twitterLoginButton.setCallback(new Callback<TwitterSession>() { @Override public void success(Result<TwitterSession> result) { // Do something with result, which provides a TwitterSession for making API calls } @Override public void failure(TwitterException exception) { // Do something on failure } }); |
7. Next, pass the result of the authentication Activity back to the button using below code.
1 2 3 4 5 6 7 |
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Pass the activity result to the login button. twitterLoginButton.onActivityResult(requestCode, resultCode, data); } |
NOTE : If your are using the TwitterLoginButton in a Fragment, use the following steps instead in your Activity.
1 2 3 4 5 6 7 8 9 10 11 |
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Pass the activity result to the fragment, which will then pass the result to the login // button. Fragment fragment = getFragmentManager().findFragmentById(R.id.your_fragment_id); if (fragment != null) { fragment.onActivityResult(requestCode, resultCode, data); } } |
8. By doing above steps you will be able to authenticate your app with Twitter account. Now if you want to access the User Email as well then use the below code after authenticating Twitter Account.
NOTE : Before using this feature, ensure that “Request email addresses from users” is checked for your Twitter app and User is having TwitterSession.
1 2 3 4 5 6 7 8 9 10 11 12 |
TwitterAuthClient authClient = new TwitterAuthClient(); authClient.requestEmail(session, new Callback<String>() { @Override public void success(Result<String> result) { // Do something with the result, which provides the email address } @Override public void failure(TwitterException exception) { // Do something on failure } }); |
9. Once the user authentication successful, a TwitterSession is provided in the success result. This TwitterSession will contain a token, secret, username, and user ID of the user and becomes the active session and is automatically persisted. If you need to retrieve the TwitterSession at a later time, you may do so using the SessionManager.
1 2 3 4 |
TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession(); TwitterAuthToken authToken = session.getAuthToken(); String token = authToken.token; String secret = authToken.secret; |
10. If you want to fetch User other details including Profile picture (as in all the above APIs Twitter doesn’t provide User profile picture), user name ,etc the use the below code once user is successfully authenticated else the API won’t work.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(); Call<User> call = twitterApiClient.getAccountService().verifyCredentials(true, false, true); call.enqueue(new Callback<User>() { @Override public void success(Result<User> result) { // Do something with result, which provides a User } @Override public void failure(TwitterException exception) { // Do something on failure } }); |
11. Finally full source code of MainActivity.java includes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
package com.twitter_auth_demo; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import com.twitter.sdk.android.core.Callback; import com.twitter.sdk.android.core.Result; import com.twitter.sdk.android.core.TwitterApiClient; import com.twitter.sdk.android.core.TwitterCore; import com.twitter.sdk.android.core.TwitterException; import com.twitter.sdk.android.core.TwitterSession; import com.twitter.sdk.android.core.identity.TwitterAuthClient; import com.twitter.sdk.android.core.identity.TwitterLoginButton; import com.twitter.sdk.android.core.models.User; import retrofit2.Call; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private TwitterLoginButton twitterLoginButton; private ImageView userProfileImageView; private TextView userDetailsLabel; //twitter auth client required for custom login private TwitterAuthClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //initialize twitter auth client client = new TwitterAuthClient(); //find the id of views twitterLoginButton = findViewById(R.id.default_twitter_login_button); userProfileImageView = findViewById(R.id.user_profile_image_view); userDetailsLabel = findViewById(R.id.user_details_label); //NOTE : calling default twitter login in OnCreate/OnResume to initialize twitter callback defaultLoginTwitter(); } /** * method to do Default Twitter Login */ public void defaultLoginTwitter() { //check if user is already authenticated or not if (getTwitterSession() == null) { //if user is not authenticated start authenticating twitterLoginButton.setCallback(new Callback<TwitterSession>() { @Override public void success(Result<TwitterSession> result) { // Do something with result, which provides a TwitterSession for making API calls TwitterSession twitterSession = result.data; //call fetch email only when permission is granted fetchTwitterEmail(twitterSession); } @Override public void failure(TwitterException exception) { // Do something on failure Toast.makeText(MainActivity.this, "Failed to authenticate. Please try again.", Toast.LENGTH_SHORT).show(); } }); } else { //if user is already authenticated direct call fetch twitter email api Toast.makeText(this, "User already authenticated", Toast.LENGTH_SHORT).show(); fetchTwitterEmail(getTwitterSession()); } } public void customLoginTwitter(View view) { //check if user is already authenticated or not if (getTwitterSession() == null) { //if user is not authenticated start authenticating client.authorize(this, new Callback<TwitterSession>() { @Override public void success(Result<TwitterSession> result) { // Do something with result, which provides a TwitterSession for making API calls TwitterSession twitterSession = result.data; //call fetch email only when permission is granted fetchTwitterEmail(twitterSession); } @Override public void failure(TwitterException e) { // Do something on failure Toast.makeText(MainActivity.this, "Failed to authenticate. Please try again.", Toast.LENGTH_SHORT).show(); } }); } else { //if user is already authenticated direct call fetch twitter email api Toast.makeText(this, "User already authenticated", Toast.LENGTH_SHORT).show(); fetchTwitterEmail(getTwitterSession()); } } /** * Before using this feature, ensure that “Request email addresses from users” is checked for your Twitter app. * * @param twitterSession user logged in twitter session */ public void fetchTwitterEmail(final TwitterSession twitterSession) { client.requestEmail(twitterSession, new Callback<String>() { @Override public void success(Result<String> result) { //here it will give u only email and rest of other information u can get from TwitterSession userDetailsLabel.setText("User Id : " + twitterSession.getUserId() + "\nScreen Name : " + twitterSession.getUserName() + "\nEmail Id : " + result.data); } @Override public void failure(TwitterException exception) { Toast.makeText(MainActivity.this, "Failed to authenticate. Please try again.", Toast.LENGTH_SHORT).show(); } }); } /** * call Verify Credentials API when Twitter Auth is successful else it will go in exception block * this metod will provide you User model which contain all user information * * @param view calling view */ public void fetchTwitterImage(View view) { //check if user is already authenticated or not if (getTwitterSession() != null) { //fetch twitter image with other information if user is already authenticated //initialize twitter api client TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(); //Link for Help : https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials //pass includeEmail : true if you want to fetch Email as well Call<User> call = twitterApiClient.getAccountService().verifyCredentials(true, false, true); call.enqueue(new Callback<User>() { @Override public void success(Result<User> result) { User user = result.data; userDetailsLabel.setText("User Id : " + user.id + "\nUser Name : " + user.name + "\nEmail Id : " + user.email + "\nScreen Name : " + user.screenName); String imageProfileUrl = user.profileImageUrl; Log.e(TAG, "Data : " + imageProfileUrl); //NOTE : User profile provided by twitter is very small in size i.e 48*48 //Link : https://developer.twitter.com/en/docs/accounts-and-users/user-profile-images-and-banners //so if you want to get bigger size image then do the following: imageProfileUrl = imageProfileUrl.replace("_normal", ""); ///load image using Picasso Picasso.with(MainActivity.this) .load(imageProfileUrl) .placeholder(R.mipmap.ic_launcher_round) .into(userProfileImageView); } @Override public void failure(TwitterException exception) { Toast.makeText(MainActivity.this, "Failed to authenticate. Please try again.", Toast.LENGTH_SHORT).show(); } }); } else { //if user is not authenticated first ask user to do authentication Toast.makeText(this, "First to Twitter auth to Verify Credentials.", Toast.LENGTH_SHORT).show(); } } /** * get authenticates user session * * @return twitter session */ private TwitterSession getTwitterSession() { TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession(); //NOTE : if you want to get token and secret too use uncomment the below code /*TwitterAuthToken authToken = session.getAuthToken(); String token = authToken.token; String secret = authToken.secret;*/ return session; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Pass the activity result to the twitterAuthClient. if (client != null) client.onActivityResult(requestCode, resultCode, data); // Pass the activity result to the login button. twitterLoginButton.onActivityResult(requestCode, resultCode, data); } } |
12. Don’t forget to provide INTERNET permission in AndroidManifest.xml file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.twitter_auth_demo"> <!-- permission required to do Twitter Auth --> <uses-permission android:name="android.permission.INTERNET" /> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
13. Finally all done , now you can also integrate Twitter to your Android app.
Thanks.
NOTE : After downloading don’t forget to place your API Key and Secret inside strings.xml.
Subscribe to us and get the latest news.
7 Comments
Soon
Friday, August 31st, 2018I found almost no information about twitter login for android, and also I could not find the twitter’s documentation guide that teachs how to integrate twitter login in android. Then, you saved me. Thank you for the great article!
António Pereira
Thursday, May 23rd, 2019Got a lot of errors like:
Duplicate class android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat found in modules classes.jar (com.android.support:support-compat:28.0.0) and classes.jar (com.android.support:support-v4:23.1.1)
…
Any idea?
Dr. Droid
Friday, May 24th, 2019Hi Antonio,
You have to use only one dependencies with same like as you mentioned com.android.support:support-compat:28.0.0 com.android.support:support-v4:23.1.1 both are same and having different versions. So try to remove one and sync again.
Thanks
Vikram
Tuesday, June 2nd, 2020E/Twitter: Authorization completed with an error
com.twitter.sdk.android.core.TwitterAuthException: Authorize failed.
at com.twitter.sdk.android.core.identity.AuthHandler.handleOnActivityResult(AuthHandler.java:98)
at com.twitter.sdk.android.core.identity.TwitterAuthClient.onActivityResult(TwitterAuthClient.java:143)
at NewMyProfileFragment.onActivityResult(NewMyProfileFragment.kt:431)
Dr. Droid
Friday, June 5th, 2020Hi Vikram,
Make sure you followed each step and added a callback scheme as well?
Thanks
Yumna Desai
Tuesday, November 16th, 2021Hi, do you know of a link to show me how to embed tweets from a certain account on Andriod studio?
Dr. Droid
Tuesday, November 23rd, 2021Hi Yumna,
Please have a look here: https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/introduction
Thanks