Android Twitter integration tutorial using Fabric Android 09.01.2017

android_twitter.png Integrating Twitter in your Android application will make user easily login into your app using their Twitter account which avoids filling a long registration forms.

In this example, we will see how we can use Fabric via Android Studio in order to make an application that

  1. Logs in
  2. Show timeline
  3. Post a tweet

We are going to make an application with three activities. The first one is to perform the login and control next action after login, the second one is to tweet a comment and third one is to view timeline.

To follow along, you should have the following set up:

  1. Twitter account
  2. Fabric account

Twitter provides an Android Studio plugin named Fabric. Fabric is Twitter's framework for developing mobile applications. It provides a set of tools to make mobile development easier and more streamlined. It includes crash reporting, beta distribution, mobile analytics, etc. The Fabric plugin comes with a set of wizards to help in the integration of its features.

Create Twitter application

In order to implement Twitter in your application you need Twitter Consumer Key and Consumer Secret which are used to make Twitter API calls. So register a new Twitter application and get the keys.

  1. Go to apps.twitter.com and register a new application.
  2. Fill application name, description and website. Give some url in the Callback URL field to make the app as browser app. If you leave it as blank it will act as Desktop app which won't work in mobile device. If you have your own website, you can use its address here. If you don't, you can simply type in http://example.com.
  3. Under the Permissions tab change the access type to Read, Write and Access direct messages.
  4. Click on the Keys and Access Tokens tab and make copy of your Consumer Key and Consumer Secret.

Import Fabric plugin into Android Studio

We have to install the Fabric plugin for Android Studio.

  1. Open File -> Settings ... -> Plugins
  2. Click Browse repositories ... and type Fabric
  3. Click Install
  4. Restart Android Studio

Next step is adding Twitter to your Android project.

  1. Once your project is loaded, click on the Fabric icon from the top toolbar in Android Studio.
  2. Click on the power button.
  3. Select organization and click on next.
  4. Now from the list click on Twitter.
  5. Now accept the license agreement and click on I already have an account.
  6. Now enter your API KEY and API SECRET and click on next.
  7. Now just click on apply.
  8. Now your project will sync with gradle. Wait for its completion.

Creating Login activity

Check permission in AndroidManifest.xml file

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

Open res/layout/activity_main.xml and add TwitterLoginButton and TextView:

<?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:orientation="vertical"
    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">

    <com.twitter.sdk.android.core.identity.TwitterLoginButton
        android:id="@+id/btnTwitterLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvStatus"
        android:textSize="20sp"/>

    <Button
        android:id="@+id/btnAdd"
        android:text="Add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="addTweet"
        android:visibility="gone"/>

    <Button
        android:id="@+id/btnTimeline"
        android:text="Timeline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showTimeline"
        android:visibility="gone"/>
</LinearLayout>

Code of MainActivity

public class MainActivity extends AppCompatActivity {
    private TwitterLoginButton btnTwitterLogin;
    private TextView tvStatus;
    private Button btnAdd, btnTimeline;

    private static final String TWITTER_KEY = "KEY";
    private static final String TWITTER_SECRET = "SECRET";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
        Fabric.with(this, new Twitter(authConfig));

        setContentView(R.layout.activity_main);

        btnTwitterLogin = (TwitterLoginButton) findViewById(R.id.btnTwitterLogin);
        tvStatus = (TextView)findViewById(R.id.tvStatus);
        tvStatus.setText("Status: ready");

        btnTwitterLogin.setCallback(new Callback<TwitterSession>() {
            @Override
            public void success(Result<TwitterSession> result) {
                String output =  String.format("Your login was successful!\n%s\nAuth Token Received: %s", 
                          result.data.getUserName(), 
                          result.data.getAuthToken().token);
                tvStatus.setText(output);

                btnAdd.setVisibility(View.VISIBLE);
                btnTimeline.setVisibility(View.VISIBLE);
            }

            @Override
            public void failure(TwitterException exception) {
                tvStatus.setText("Status: login failed");
            }
        });
    }

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

    public void showTimeline(View v) {
        Intent i = new Intent(getBaseContext(), TimelineActivity.class);
        startActivity(i);
    }

    public void addTweet(View v) {
        Intent i = new Intent(getBaseContext(), TweetActivity.class);
        startActivity(i);
    }
}

To process the result of the login attempt, you must create a custom Callback. In case of a successful login attempt, display the name of the logged in user and the auth token. Both values are available from the data field of Result<TwitterSession>. To get the username of the logged in user use getUsername. Similarly, to get the auth token use getAuthToken.

Clicking the login button starts an external Activity that returns a result. To capture that result, override the onActivityResult method of the Activity and pass the arguments received to the onActivityResult method of the button.

Result

android_twitter_login.png

Creating Timeline activity

Create activity_timeline.xml layout

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

    <TextView android:id="@id/android:empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="No Tweets"/>

    <ListView android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:divider="#e1e8ed"
        android:dividerHeight="1dp"
        android:drawSelectorOnTop="false"/>
</LinearLayout>

Create TimelineActivity.java file and write the following code.

public class TimelineActivity extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timeline);

        String username = "wivn";
        final UserTimeline userTimeline = new UserTimeline.Builder()
                .screenName(username)
                .build();
        final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter(this, userTimeline);
        setListAdapter(adapter);
    }
}

Creating post Tweet activity

Create activity_tweet.xml layout

<?xml version="1.0" encoding="utf-8"?>
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/edTweet"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Send"
        android:layout_weight="1"
        android:onClick="postTweet"/>
</LinearLayout>

Create TweetActivity.java file and write the following code.

public class TweetActivity extends AppCompatActivity {
    ProgressDialog dlgWait;
    EditText edTweet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tweet);
        edTweet = (EditText) findViewById(R.id.edTweet);
    }

    public void postTweet(View v) {
        final TwitterSession session = Twitter.getSessionManager().getActiveSession();

        dlgWait = new ProgressDialog(TweetActivity.this);
        dlgWait.setMessage("Sending ...");
        dlgWait.show();

        StatusesService statusesService = TwitterCore.getInstance().getApiClient(session).getStatusesService();
        statusesService.update(edTweet.getText().toString(), null, false, null, null, null, true, false, null)
        .enqueue(new Callback<Tweet>() {
            @Override
            public void success(Result<Tweet> tweetResult) {
                Toast.makeText(TweetActivity.this, "Complete", Toast.LENGTH_SHORT).show();
                edTweet.setText("");
                dlgWait.dismiss();
            }

            public void failure(TwitterException e) {
                Toast.makeText(TweetActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                dlgWait.dismiss();
            }
        });
    }
}

Result

android_twitter_post.png