TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Integrating Twitter API in Android App

Integrating Twitter API in Android App with examples of Activity and Intent, Fragments, Menu, Service, alarm manager, storage, sqlite, xml, json, multimedia, speech, web service, telephony, animation and graphics

<< Back to ANDROID

Integrating Twitter API in Android App

In this tutorial, we will integrate the Twitter Log-in API into an Android app. For integrating Twitter API in the Android app, it requires the app Consumer Key (API Key) and Consumer Secret (API Secret). It can be generated from https://apps.twitter.com/.

Combining the Twitter API in Android app helps users for log-in using the Twitter account, share tweets, etc.

Steps to generate Twitter API Key and API Secret

1. Log-in at https://apps.twitter.com/ with your Twitter account and click on 'Create New App'.


android Twitter Integrating

2. Fill all the required detail in new open form and click on 'Create your Twitter Application'.


android Twitter Integrating

3. Select the application permission mode for our app. Here we select Read, Write and Access direct messages and click 'Update Settings'.


android Twitter Integrating

4. Now, open the 'Settings' tab and fill all the required details and click 'Update Settings'.


android Twitter Integrating

5. Now again, open Permissions tab and enable 'Request email from users' and click again 'Update settings'.


android Twitter Integrating

6. Now, open 'Key and Access Tokens' tab, we will find our app 'Consumer Key' and 'Consumer Secrets'.


android Twitter Integrating

Example to Integrate Twitter Login in Android app

Let's create an example of integrating login through a Twitter account in an Android app.

Create an Android app and add the following twitter dependencies in 'build.gradel' (Module) file.

compile 'com.twitter.sdk.android:twitter:3.1.1'
compile 'com.twitter.sdk.android:twitter-core:3.1.1'

Make sure that "jcenter()" is present in 'build.gradel' (Project) file.

strings.xml

Place the 'Consumer Key' and 'Consumer Secret' of our app generated by Twitter in 'strings.xml' file.

<resources>
    <string name="app_name">Twitter Login Demo</string>
    <string name="com.twitter.sdk.android.CONSUMER_KEY">Fw4cXXXXXXXXXXX</string>
    <string name="com.twitter.sdk.android.CONSUMER_SECRET">Pnr7XXXXXXXXXXX</string>
</resources>

activity_main.xml

Add the Twitter login button provided by Twitter API in 'activity_main.xml' file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="example.com.twitterlogindemo.MainActivity">


    <com.twitter.sdk.android.core.identity.TwitterLoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="40dp"/>

</RelativeLayout>

MainActivity.java

Add the following code in 'MainActivity.java' file. We should place 'Twitter.initialize(this)' code before 'setContentView(R.layout.activity_main)'. If we place 'Twitter.initialize(this)' after the 'setContentView(R.layout.activity_main)' then our Twitter button will disable.

package example.com.twitterlogindemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.core.TwitterAuthToken;
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.TwitterLoginButton;

public class MainActivity extends AppCompatActivity {

    TwitterLoginButton loginButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Twitter.initialize(this);
        setContentView(R.layout.activity_main);

        loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
        loginButton.setCallback(new Callback() {
            @Override
            public void success(Result result) {
                // Do something with result, which provides a TwitterSession for making API calls
                TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
                TwitterAuthToken authToken = session.getAuthToken();
                //String token = authToken.token;
              //  String secret = authToken.secret;

                loginMethod(session);
            }

            @Override
            public void failure(TwitterException exception) {
                // Do something on failure
                Toast.makeText(getApplicationContext(),"Login fail",Toast.LENGTH_LONG).show();
            }
        });
    }

    public void loginMethod(TwitterSession twitterSession){
            String userName=twitterSession.getUserName();
            Intent intent= new Intent(MainActivity.this,HomeActivity.class);
            intent.putExtra("username",userName);
            startActivity(intent);
    }
    @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);
    }
}

Now we create another Activity for redirecting user after successful login.

activity_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="example.com.twitterlogindemo.HomeActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to HomePage"
        android:textSize="20dp"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="40dp"

       />

    <TextView
        android:id="@+id/nametextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:layout_below="@+id/textView"
        android:layout_marginTop="48dp"
        android:textSize="16dp"
        android:text="" />
</RelativeLayout>

HomeActivity.java

In this class, we will display the user name received from 'MainActivity.java' file in TextView.

package example.com.twitterlogindemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class HomeActivity extends AppCompatActivity {
    TextView name;
    String user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        user=getIntent().getStringExtra("username");
        name=(TextView)findViewById(R.id.nametextView);
        name.setText(user);

    }
}

Output:

android Twitter Integrating android Twitter Integrating
android Twitter Integrating android Twitter Integrating
Next TopicAndroid Versions




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf