Social SignIn [Part - 2] - Fabric SDK For Twitter Login

Fabric SDK is newer SDK introduced by Twitter for Mobile Integration. Fabric SDK comes with many combined projects like Twitter Authentication For Twitter API, Crashlytics For crash reports and analysis, MoPub for advertisement etc. Before this sdk or alternative of this is Twitter4J library for Twitter API.

androprogrammer.com


This is 2nd Part of tutorial series so i am not going through all project setup steps you can find it at Social SignIn [Part - 1] - Integrate Google plus in Android App. To add Twitter authentication in your application you have to create application at Fabric.io and you can configure about which project you want to integrate into your project from Fabric sdk. Once you completely create application it will even help you to integrate Fabric sdk using Android Studio Plugins.

Once it gets installed  you can see icons like this image in toolbar. 

Just click on it and it will start like setup wizard you just have to click next. if you don't have developer account it will even create for you from Android Studio Plugin.


Wow That's easy... right ?

No, once you integrate all those things into project you might come across gradle error like this.
Error:Execution failed for task ':app:fabricGenerateResourcesDebug'.
> Crashlytics Developer Tools error.
Don't worry just comment this line in app > build.gradle file.
apply plugin: 'io.fabric'

If you only want to add Twitter login then only comment it. if you want other packages also then you have to use Fabric sdk. So now setup is done now let's see how you can add twitter button in your layout. If you want same twitter button added by Fabric sdk in your project you can skip this step. In this tutorial i have created TwitterLoginHelper class which actually does all things for me and for my view it just return result of that. But with TwitterLoginButton you don't have to do any thing. it has setCallBack method which allows you to get result into activity. but i am following MVP where my view don't know about callbacks and all it just consume result after all manipulation. Have look at my TwitterLoginHelper class.

TwitterLoginHelper.java 
package com.androprogrammer.socialsignin.util.helpers;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.androprogrammer.socialsignin.listeners.SocialConnectListener;
import com.androprogrammer.socialsignin.model.UserLoginDetails;
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.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterAuthClient;
import com.twitter.sdk.android.core.services.AccountService;

/**
 * Created by Wasim on 24-Jan-16.
 */
public class TwitterLoginHelper {

    private TwitterAuthClient client;

    private AppCompatActivity activity;
    private UserLoginDetails userData;

    private SocialConnectListener userCallbackListener;

    private int identifier;
    private static final String TAG = "TwitterLoginHelper";

    public void createConnection(AppCompatActivity mActivity) {

        this.activity = mActivity;
        userData = new UserLoginDetails();
        client = new TwitterAuthClient();

    }

    public TwitterAuthClient getClient() {
        return client;
    }

    public void onActivityResult(int requestCode,int resultCode, Intent data) {

        client.onActivityResult(requestCode,resultCode,data);

    }

    public void signIn(final int mIdentifier) {

        if (client != null)
        {
            identifier = mIdentifier;
            client.authorize(activity, new Callback <twittersession>() {
                @Override
                public void success(Result <twittersession> twitterSessionResult) {
                    Log.d(TAG, "Logged with twitter");
                    final TwitterSession session = twitterSessionResult.data;

                    AccountService ac = Twitter.getApiClient(twitterSessionResult.data).getAccountService();
                    ac.verifyCredentials(true, true, new Callback <com .twitter.sdk.android.core.models.user>() {
                        @Override
                        public void success(Result <com .twitter.sdk.android.core.models.user> result) {

                            userData.setIsSocial(true);
                            userData.setIsAndroid(true);
                            userData.setTwittersLogin(true);
                            userData.setTwitterID(String.valueOf(session.getUserId()));
                            userData.setFullName(result.data.name);
                            //userData.setEmail(result.data.email);
                            userData.setEmail(getUserEmail(session));
                            userData.setUserImageUrl(result.data.profileImageUrl);

                            if (userCallbackListener != null)
                            {
                                userCallbackListener.onUserConnected(identifier,userData);
                            }
                        }

                        @Override
                        public void failure(TwitterException e) {

                            if (userCallbackListener != null)
                            {
                                userCallbackListener.onConnectionError(identifier,e.getMessage());
                            }

                        }
                    });

                    /**/


                }

                @Override
                public void failure(TwitterException e) {
                    Log.e(TAG, "Failed login with twitter");
                    e.printStackTrace();
                    if (userCallbackListener != null)
                    {
                        userCallbackListener.onConnectionError(identifier,e.getMessage());
                    }
                }
            });
        }

    }

    public void signOut()
    {
        Twitter.getSessionManager().clearActiveSession();
    }

    public void setUserCallbackListener(SocialConnectListener userCallbackListener) {
        this.userCallbackListener = userCallbackListener;
    }

    private String getUserEmail(TwitterSession session)
    {
        final String[] userEmail = new String[1];

        client.requestEmail(session, new Callback <string>() {
            @Override
            public void success(Result <string> result) {
                // Do something with the result, which provides the email address
                Log.d(TAG,"Email found - " + result.toString());
                userEmail[0] = result.data;
            }

            @Override
            public void failure(TwitterException exception) {
                // Do something on failure
                Log.d(TAG,"Email not found - " + exception.getMessage());
                userEmail[0] = "";
            }
        });

        return userEmail[0];
    }
}


This class actually does every thing for me and it is like central class for all operation of Twitter. you can create method here for getTweets or user timeline etc. benefits of such way is you don't have to create Twitter client object for different task into different classes. To get user email your app has to be on their whitlist applications.  To request email you have to submit this form.

Well now have look at below code where you can see how i have user this class.

private void startTwitterLogin() {
 Log.d("onclick", "clicked");
 if (Utility.isConnectivityAvailable(LoginActivity.this)) {
  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    layout_full_twitter.setBackgroundColor(getResources().getColor(R.color.view_disable));
    layout_full_twitter.setEnabled(false);
    layout_twitter.setVisibility(View.GONE);
    pb_twitterLoader.setVisibility(View.VISIBLE);
   }
  });

  twitterHelper.createConnection(LoginActivity.this);
  twitterHelper.signIn(TWITTER_SIGN_IN);

 } else {
  Utility.showToast(LoginActivity.this,getString(R.string.msg_noInternet));
 }
}

So That's it from my side. this tutorial only covers Twitter authentication but for more like get tweets or timeline or post tweet etc subscribe to our news latter so you can get more tutorials in your inbox.

I have created this project in Kotlin language also so if you want please check out here.

Source Code

Keep coding... :)

0 comments :

Post a comment