Search Tutorials

Tuesday 16 June 2015

Android Twitter Fabric SDK Integration with user details in Android Studio

Recently, I updated Facebook SDK integration with user details post. Now, I am going to share easy steps to integrate Twitter Fabric SDK with user details. Using Facebook and Twitter login button, you all can make a brand app. For Facebook, check Facebook login post. For twitter, steps are given below:-

1. Go to twitter site -> create an app -> fill all details -> get Consumer Key and Consumer Secret.

2. Go to fabric site (register/login to proceed) to download android studio plugin for twitter login/update status.

Note:-  Twitter official document available on twitter developer site.

3. After downloading fabric plugin, add it to android studio as per given instruction there. Restart Android studio and than create new project and click on icon generated by fabric on android studio. Select twitter login from list and click on next -> next -> finish. Most of the code/files added by fabric plugin automatically in your android project.

Android Twitter Fabric SDK Integration with user details in Android Studio

Now open your layout file and add a button for twitter login and assign id name "button" than use below code in your activity for twitter login and user details:-

package com.iifm.favcy; //your package name

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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.TwitterAuthConfig;
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.models.User;
import io.fabric.sdk.android.Fabric;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;

public class FavcyLogin extends ActionBarActivity {

    //paste your app secret key and consumer key here
    private static final String TWITTER_KEY = "YvG9AEBYV280Z5i0vVMblTbAR";
    private static final String TWITTER_SECRET = "f2JiqPMXxzC4n8xW9oIMroItGeWdhLePbN0yjezcqevdrxKGvc";
    private TwitterAuthClient client;

    private Button twitter_button;
    ProgressDialog progress;
    private String twitter_id, twitter_name, t_full_name, t_profile_image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            getSupportActionBar().hide();
        }catch (NullPointerException e){

        }
        setContentView(R.layout.activity_favcy_login);

        twitter_button=(Button)findViewById(R.id.button);
        progress=new ProgressDialog(FavcyLogin.this);
        progress.setMessage(getResources().getString(R.string.please_wait_favcy));
        progress.setIndeterminate(false);
        progress.setCancelable(false);
        twitter_id=twitter_name=t_full_name=t_profile_image="";

        //for twitter
        TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
        Fabric.with(this, new com.twitter.sdk.android.Twitter(authConfig));
        client = new TwitterAuthClient();


        //twitter button login
        twitter_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!isConnected()){
                    Toast.makeText(FavcyLogin.this, getResources().getString(R.string.network_connection_error_favcy), Toast.LENGTH_SHORT).show();
                    return;
                }
                client.authorize(FavcyLogin.this, new Callback<TwitterSession>() {
                    @Override
                    public void success(Result<TwitterSession> result) {
                        progress.show();
                        twitter_name = result.data.getUserName();
                        twitter_id = result.data.getUserId() + "";

                        TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
                        twitterApiClient.getAccountService().verifyCredentials(false, false, new Callback<User>() {
                            @Override
                            public void success(Result<User> userResult) {
                                t_full_name = userResult.data.name;
                                t_profile_image = userResult.data.profileImageUrl;

                                Intent i=new Intent(FavcyLogin.this, FavcyRegistration.class);
                                i.putExtra("type","twitter");
                                i.putExtra("twitter_name",twitter_name);
                                i.putExtra("twitter_id",twitter_id);
                                i.putExtra("t_profile_image",t_profile_image);
                                i.putExtra("t_full_name",t_full_name);

                                progress.dismiss();
                                startActivity(i);
                                finish();
                            }

                            @Override
                            public void failure(TwitterException e) {
                                Toast.makeText(FavcyLogin.this,getResources().getString(R.string.login_failed_favcy),Toast.LENGTH_SHORT).show();
                                progress.dismiss();
                            }
                        });
                    }

                    @Override
                    public void failure(TwitterException e) {
                        Toast.makeText(FavcyLogin.this,getResources().getString(R.string.login_failed_favcy),Toast.LENGTH_SHORT).show();
                        progress.dismiss();
                    }
                });
            }
        });

    }

    //for twitter callback result.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        client.onActivityResult(requestCode,resultCode,data);
    }

    private boolean isConnected(){
        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        return isConnected;
    }
}

Add permissions in app android manifest XML file:-

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

Now all are done. Comment below if you have any doubt or problem. Feel free to share it.

Related programs:-

Add Facebook SDK in Android Application

Add Google AdMob Ads in Android App & Earn Money

Advance Android Google Map 2 Tutorial with Examples - Part 1

Start Working on Linphone Android

Call log details after ending call using ContentObserver & PhoneStateListener

22 comments:

  1. A very useful and nice tutorial indeed, thanks.

    ReplyDelete
    Replies
    1. @Md Mohsin, Thanks for your nice tutorial, What about FavcyRegistration.class ?

      Delete
  2. Invalid json:

    Desktop applications only support the oauth_callback value 'oob'
    /oauth/request_token


    got this error...


    Any solution?

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Awesome post.It works for me.Great job, please keep it up and all the best.

    ReplyDelete
  5. Thanks for your great tutorial, But, What about FavcyRegistration.class ? You have not given Code for this Registration Activity.

    ReplyDelete
    Replies
    1. Hi Jaimin Modi, FavcyRegistration.java file is not necessary in this tutorial. You can make welcome activity on successful login or show toast message.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. Code to Share and Logout ?

      Delete
    4. Please check on twitter developer site.

      Delete
  6. unable to login or signup in fabric???

    ReplyDelete
  7. Not getting email what should i do??

    ReplyDelete
  8. Error:(430, 53) error: method verifyCredentials in interface AccountService cannot be applied to given types;
    required: Boolean,Boolean
    found: boolean,boolean,>
    reason: actual and formal argument lists differ in length

    ReplyDelete
    Replies
    1. Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
      > Compilation failed; see the compiler error output for details.

      Delete
    2. CAnanyone help me ?? im stuck in this problem

      Delete

  9. when i hover on the (callback) USER then i get this line in popup message. can anyone help me in this ? ? ?

    :POPUP MESSAGE:
    Anonymus sdk.android.core.models.User

    ReplyDelete
    Replies
    1. Error 1:

      Error:(430, 53) error: method verifyCredentials in interface AccountService cannot be applied to given types;
      required: Boolean,Boolean
      found: boolean,boolean,>
      reason: actual and formal argument lists differ in length

      Error 2:
      Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
      > Compilation failed; see the compiler error output for details.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. Error:(430, 53) error: method verifyCredentials in interface AccountService cannot be applied to given types;
      required: Boolean,Boolean
      found: boolean,boolean, anonymous Callback User
      reason: actual and formal argument lists differ in length

      Delete

Back to Top