Hello friends, today we will learn how we can integrate twitter login to our android application. So in this twitter login android tutorial we will learn how we can add a login with twitter feature to our application.
Twitter has a mobile development platform called Fabric. Through fabric we can get Twitter SDK for Android.
Twitter Login Android – Video Demo
You can check this video to know what you will be creating through this tutorial.
So if you wanna create this move ahead.
Creating Twitter Fabric Account and Twitter App
- Go to this link and create a twitter fabric account.
- After signup login to twitter fabric.
- Now we need a twitter app, so go to Twitter Application Management.
- Click on Create New App and fill the form to create your app.
- After the creation you will get your API Key and API Secret.
Installing Twitter Fabric in Android Studio
- Open Android Studio.
- Go to file -> settings
- Click on Browser repositories.
- Search for Fabric
- Install Fabric for Android Studio and Restart Android Studio to complete the installation.
Adding Twitter to Your Android Project
- Now we are done with the configuration for this twitter login android project, now lets create our android project. I created TwitterLoginSample.
- Once your project is loaded, click on the fabric icon from the top to add Android Twitter Client (see the snapshot below).
- Click on the power button now.
- Select organization and click on next.
- Now from the list click on Twitter.
- Now accept the license agreement and click on I already have an account.
- Now enter your API KEY and API SECRET and click on next.
- Â Now just click on apply.
- Now your project will sync with gradle. Wait for its completion.
Coding Twitter Login Android Project
- All the configurations are done. Lets code our app now.
- Twitter provides a login button. So go to your application’s layout file i.e. activity_main.xml and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="net.simplifiedcoding.twitterloginsample.MainActivity"> <com.twitter.sdk.android.core.identity.TwitterLoginButton android:id="@+id/twitterLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" /> </LinearLayout> |
- The above code will give you the following layout.
- After successful login user will move to a new activity. So create a new activity named ProfileActivity (Right Click -> New -> Activity -> Empty Activity).
- Now come to MainActivity.java and write the following code.
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 |
package net.simplifiedcoding.twitterloginsample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.twitter.sdk.android.Twitter; import com.twitter.sdk.android.core.Callback; import com.twitter.sdk.android.core.Result; import com.twitter.sdk.android.core.TwitterAuthConfig; import com.twitter.sdk.android.core.TwitterAuthToken; import com.twitter.sdk.android.core.TwitterException; import com.twitter.sdk.android.core.TwitterSession; import com.twitter.sdk.android.core.identity.TwitterLoginButton; import com.twitter.sdk.android.core.models.User; import io.fabric.sdk.android.Fabric; public class MainActivity extends AppCompatActivity { //This is your KEY and SECRET //And it would be added automatically while the configuration private static final String TWITTER_KEY = "YOUR TWITTER KEY"; private static final String TWITTER_SECRET = "YOUR TWITTER SECRET"; //Tags to send the username and image url to next activity using intent public static final String KEY_USERNAME = "username"; public static final String KEY_PROFILE_IMAGE_URL = "image_url"; //Twitter Login Button TwitterLoginButton twitterLoginButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Initializing TwitterAuthConfig, these two line will also added automatically while configuration we did TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); Fabric.with(this, new Twitter(authConfig)); setContentView(R.layout.activity_main); //Initializing twitter login button twitterLoginButton = (TwitterLoginButton) findViewById(R.id.twitterLogin); //Adding callback to the button twitterLoginButton.setCallback(new Callback<TwitterSession>() { @Override public void success(Result<TwitterSession> result) { //If login succeeds passing the Calling the login method and passing Result object login(result); } @Override public void failure(TwitterException exception) { //If failure occurs while login handle it here Log.d("TwitterKit", "Login with Twitter failure", exception); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //Adding the login result back to the button twitterLoginButton.onActivityResult(requestCode, resultCode, data); } //The login function accepting the result object public void login(Result<TwitterSession> result) { //Creating a twitter session with result's data TwitterSession session = result.data; //Getting the username from session final String username = session.getUserName(); //This code will fetch the profile image URL //Getting the account service of the user logged in Twitter.getApiClient(session).getAccountService() .verifyCredentials(true, false, new Callback<User>() { @Override public void failure(TwitterException e) { //If any error occurs handle it here } @Override public void success(Result<User> userResult) { //If it succeeds creating a User object from userResult.data User user = userResult.data; //Getting the profile image url String profileImage = user.profileImageUrl.replace("_normal", ""); //Creating an Intent Intent intent = new Intent(MainActivity.this, ProfileActivity.class); //Adding the values to intent intent.putExtra(KEY_USERNAME,username); intent.putExtra(KEY_PROFILE_IMAGE_URL, profileImage); //Starting intent startActivity(intent); } }); } } |
- Now come to activity_profile.xml (Layout file of second activity) and write the following code.
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 |
<?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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="net.simplifiedcoding.twitterloginsample.ProfileActivity"> <com.android.volley.toolbox.NetworkImageView android:id="@+id/profileImage" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textViewUsername" android:layout_margin="@dimen/activity_horizontal_margin" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> |
- As you can see I am using a NetworkImageView, this is of Volley. So we also need to add volley to our project dependencies. So open build.gradle file add volley and sync your project.
1 2 3 |
compile 'com.mcxiaoke.volley:library-aar:1.0.0' |
- To load image from URL we also need to create a Custom Volley Request. Same as we created in many tutorials published here.
- So create a new class named CustomVolleyRequest and write the following code.
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 |
package net.simplifiedcoding.twitterloginsample; import android.content.Context; import android.graphics.Bitmap; import android.support.v4.util.LruCache; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; /** * Created by Belal on 12/5/2015. */ public class CustomVolleyRequest { private static CustomVolleyRequest customVolleyRequest; private static Context context; private RequestQueue requestQueue; private ImageLoader imageLoader; private CustomVolleyRequest(Context context) { this.context = context; this.requestQueue = getRequestQueue(); imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() { private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20); @Override public Bitmap getBitmap(String url) { return cache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { cache.put(url, bitmap); } }); } public static synchronized CustomVolleyRequest getInstance(Context context) { if (customVolleyRequest == null) { customVolleyRequest = new CustomVolleyRequest(context); } return customVolleyRequest; } public RequestQueue getRequestQueue() { if (requestQueue == null) { Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024); Network network = new BasicNetwork(new HurlStack()); requestQueue = new RequestQueue(cache, network); requestQueue.start(); } return requestQueue; } public ImageLoader getImageLoader() { return imageLoader; } } |
- Finally come to ProfileActivity.java and write the following code.
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 |
package net.simplifiedcoding.twitterloginsample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; public class ProfileActivity extends AppCompatActivity { //Image Loader object private ImageLoader imageLoader; //NetworkImageView Ojbect private NetworkImageView profileImage; //TextView object private TextView textViewUsername; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); //Initializing views profileImage = (NetworkImageView) findViewById(R.id.profileImage); textViewUsername = (TextView) findViewById(R.id.textViewUsername); //Getting the intent Intent intent = getIntent(); //Getting values from intent String username = intent.getStringExtra(MainActivity.KEY_USERNAME); String profileImageUrl = intent.getStringExtra(MainActivity.KEY_PROFILE_IMAGE_URL); //Loading image imageLoader = CustomVolleyRequest.getInstance(this).getImageLoader(); imageLoader.get(profileImageUrl, ImageLoader.getImageListener(profileImage, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert)); profileImage.setImageUrl(profileImageUrl, imageLoader); //Setting the username in textview textViewUsername.setText("@"+username); } } |
- Thats it now run your project.
- And its working absolutely fine (y). If you are having troubles you can get my twitter login android project from GitHub Repository. Go to the below link to get this Twitter Login Android Project.
Get this Twitter Login Android Project Source from GitHub
[sociallocker id=1372] Twitter Login Android Sample Application [/sociallocker]
Some More Android Application Development You Should CheckÂ
So thats all for this Twitter Login Android Tutorial. Support if you liked my tutorials by sharing this to your social networks. And don’t hesitate to leave your comments if having any queries regarding this Twitter Login Android Tutorial. Thank You 🙂