Twitter Integration Using Fabric In Android (Part 1)

Fabric-Color-Transparent

Fabric is a flexible, modular set of mobile development tools called “Kits” that help you make your app more stable, add social features like sharing and login, and turn your app into a business with easy monetization.

In this tutorial, we will learn how to use fabric to login with twitter, show tweets and share on twitter and a lot more.

Screenshot from 2015-07-23 00:29:42

Select one of the onboarding tool i.e. Android Studio or Eclipse IDE.

Follow the instructions available on the links:

For Eclipse: https://fabric.io/downloads/eclipse

For Android Studio: https://fabric.io/downloads/android-studio

After adding fabric plugin in eclipse login and choose your project from the list of projects in your workspace.

Screenshot from 2015-07-23 00:45:12

Install second option i.e twitter and follow the instructions. Required code and kits will automatically be added to your project.

Screenshot from 2015-07-23 00:45:40

Following code will be added to your launcher activity.

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import io.fabric.sdk.android.Fabric;
public class Splash extends Activity {
 private static final String TWITTER_KEY = "YOUR TWITTER KEY";
 private static final String TWITTER_SECRET = "YOUR TWITTER SECRET";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
   Fabric.with(this, new Twitter(authConfig));
   setContentView(R.layout.splash);
}
}

Create a new activity named LoginActivity.java

import android.app.Activity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.crashlytics.android.Crashlytics;
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.TwitterAuthClient;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
import com.twitter.sdk.android.core.models.User;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import io.fabric.sdk.android.Fabric;
import retrofit.client.Response;

public class LoginActivity extends Activity {

    TwitterLoginButton loginButton;
    SharedPreferences shared;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        shared = getSharedPreferences("demotwitter", Context.MODE_PRIVATE);
        loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
        
        loginButton.setCallback(new Callback<TwitterSession>() {
            @Override
            public void success(Result<TwitterSession> result) {
                // Do something with result, which provides a TwitterSession for
                // making API calls
                TwitterSession session = Twitter.getSessionManager()
                        .getActiveSession();
                TwitterAuthToken authToken = session.getAuthToken();
                String token = authToken.token;
                String secret = authToken.secret;

//Here we get all the details of user's twitter account

                System.out.println(result.data.getUserName()
                        + result.data.getUserId());
                Twitter.getApiClient(session).getAccountService()
                        .verifyCredentials(true, false, new Callback<User>() {

                            @Override
                            public void success(Result<User> userResult) {

                                User user = userResult.data;
//Here we get image url which can be used to set as image wherever required.      
                 System.out.println(user.profileImageUrl+" "+user.email);
                            }

                            @Override
                            public void failure(TwitterException e) {

                            }

                        });
                shared.edit().putString("tweetToken", token).commit();
                shared.edit().putString("tweetSecret", secret).commit();
                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
                        System.out.println(result.toString());
                        Log.d("Result", result.toString());
                        Toast.makeText(getApplicationContext(), result.data,
                                Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void failure(TwitterException exception) {
                        // Do something on failure
                        System.out.println(exception.getMessage());
                    }
                });
            }

            @Override
            public void failure(TwitterException exception) {
                // Do something on failure
            }
        });
  MyTwitterApiClient apiclients=new MyTwitterApiClient(session);
                apiclients.getCustomService().list(result.data.getUserId(), new Callback<Response>() {

					@Override
					public void failure(TwitterException arg0) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void success(Result<Response> arg0) {
						// TODO Auto-generated method stub
						BufferedReader reader = null;
				        StringBuilder sb = new StringBuilder();
				        try {

				            reader = new BufferedReader(new InputStreamReader(arg0.response.getBody().in()));

				            String line;

				            try {
				                while ((line = reader.readLine()) != null) {
				                    sb.append(line);
				                }
				            } catch (IOException e) {
				                e.printStackTrace();
				            }
				        } catch (IOException e) {
				            e.printStackTrace();
				        }


				        String result = sb.toString();
					System.out.println("Response is>>>>>>>>>"+result);
					try {
						JSONObject obj=new JSONObject(result);
						JSONArray ids=obj.getJSONArray("ids");
						for(int i=0;i<ids.length();i++){
						System.out.println("Id of user "+(i+1)+" is "+ids.get(i));
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					}
					
				});
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Pass the activity result to the login button.
        loginButton.onActivityResult(requestCode, resultCode, data);
    }

}

Your application should be white listed by twitter to able to access user’s email. So you can request here for that: https://support.twitter.com/forms/platform

Now for making REST Api calls using FABRIC we will use following class:

MyTwitterApiClient.java

import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterSession;


import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Query;

public class MyTwitterApiClient extends TwitterApiClient {
    public MyTwitterApiClient(TwitterSession session) {
        super(session);
    }

    /**
     * Provide CustomService with defined endpoints
     */
    public CustomService getCustomService() {
        return getService(CustomService.class);
    }
}

// example followers/list service endpoint
interface CustomService {
    @GET("/1.1/followers/ids.json")
    void list(@Query("user_id") long id, Callback<Response> cb);
}

For more information checkout the following link:

http://docs.fabric.io/android/twitter/access-rest-api.html#extensions

login.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent">

<com.twitter.sdk.android.core.identity.TwitterLoginButton 
android:id="@+id/login_button" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_centerInParent="true" />
</RelativeLayout>

6 thoughts on “Twitter Integration Using Fabric In Android (Part 1)

    1. @Amanpal
      Requesting a User’s Email Address requires your application to be whitelisted by Twitter. To request access, please visit https://support.twitter.com/forms/platform.

      Note:
      Even if the user grants access to her email address, it is not guaranteed you will get an email address. For example, if someone signed up for Twitter with a phone number instead of an email address, the email field may be empty. When this happens, the failure method will be called because there is no email address available.

      Like

      1. Amanpal Singh

        Multiple Request Options are showing when i clicked on link provided by you.Out of all request option which option is for email request.

        Thanks in Advance

        Like

      2. Please choose the last option and then fill your details over there and submit your request.

        Please subscribe to get notified regarding new posts. Thanks

        Like

  1. Michael

    Im getting this error – Error:(99, 46) error: list(long,Callback) in CustomService is defined in an inaccessible class or interface

    for this line

    apiclients.getCustomService().list(result.data.getUserId(), new Callback() {

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s