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 tutorial i explained how to integrate twitter in your android application using twitter oAuth procedure. This is very basic tutorial with simple login and updating twitter status message.

Download Code

Registering twitter app – getting Consumer Key & Consumer Secret

In order to implement twitter oAuth 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. Check the following video about creating a twitter app

1. Go to https://dev.twitter.com/apps/new and register new application. Fill application name, description and website.
2. Give some dummy 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)

android registering twitter application

3. Under the settings tab upload icon and change the access type to Read and Write.

android registering twitter application uploading icon

4. Copy Consumer Key & Consumer Secret key

android registering twitter application consumer key & secret

Downloading twitter4j library

In this tutorial to integrate twitter i used one of the most popular libraries twitter4j. You can read their official documentation to know more about it.

1. Download & extract twitter4j library from twitter4j-android-2.2.6.zip (slimmed version for Android platform). Here is the direct link

Creating new Project

In this tutorial i explained basic twitter API calls login and updating status only. If you want to integrate more api calls like reading users tweet timeline, sending direct message etc., you need to include other required .jar files too. Read more Code Examples to get know the usage.

1. Create a new project in Eclipse File New ⇒ Android ⇒ Application Project and fill the required details.
After creating project open AndroidManifest.xml file and paste the following code. I added following code to manifest file

– INTERNET Permission
– ACCESS_NETWORK_STATE Permission
– and added an Intent Filter

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.twitterconnect"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="oauth" android:host="t4jsample"/>
            </intent-filter>
        </activity>
    </application>
    
    <!-- Permission - Internet Connect -->
    <uses-permission android:name="android.permission.INTERNET" />
    
    <!-- Network State Permissions -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

</manifest>

2. Copy the required twitter4j .jar files into your project’s libs folder. In this tutorial i copied twitter4j-core-android-2.2.6 as it is the only required file in this tutorial.

android twitter4j jar files
android adding twitter4j jar files to project

3. Before getting into twitter integration i am including two quick class files to the project. Create a new class file called AlertDialogManager.java and paste the following code. This class file used to show alert dialog.

package com.androidhive.twitterconnect;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class AlertDialogManager {
	/**
	 * Function to display simple Alert Dialog
	 * @param context - application context
	 * @param title - alert dialog title
	 * @param message - alert message
	 * @param status - success/failure (used to set icon)
	 * 				 - pass null if you don't want icon
	 * */
	public void showAlertDialog(Context context, String title, String message,
			Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		if(status != null)
			// Setting alert dialog icon
			alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}
}

4. Create another class file named ConnectionDetector.java and paste the following code. This class is used to detect internet connection status.

package com.androidhive.twitterconnect;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
 
public class ConnectionDetector {
 
    private Context _context;
 
    public ConnectionDetector(Context context){
        this._context = context;
    }
 
    /**
     * Checking for all possible internet providers
     * **/
    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
 
          }
          return false;
    }
}

5. Open your activity_main.xml file and type the following code. In the following code i am placing login button, update status edittext and update status button. By default all the ui elements will be hidden except login button.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
    <!-- Twitter Login Button -->
    <Button android:id="@+id/btnLoginTwitter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Login with Twitter"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="30dip"/>
    
    <!-- user name label -->
    <TextView android:id="@+id/lblUserName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_marginTop="30dip"/>

    <!-- label update status -->
    <TextView android:id="@+id/lblUpdate" 
        android:text="Update Status"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:visibility="gone"/>
    
    <!-- Tweet EditText -->
    <EditText android:id="@+id/txtUpdateStatus"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:visibility="gone"/>
    
    <!-- Tweet Button -->
    <Button android:id="@+id/btnUpdateStatus"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Tweet"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:visibility="gone"/>
    
    <!-- Twitter Logout button -->
    <Button android:id="@+id/btnLogoutTwitter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Logout from Twitter"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="50dip"
        android:visibility="gone"/>

</LinearLayout>

6. Now open your main activity class (In my case MainActivity.java) file and type the following code. In the following code i am declaring required variables.

package com.androidhive.twitterconnect;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	// Constants
	/**
	 * Register your here app https://dev.twitter.com/apps/new and get your
	 * consumer key and secret
	 * */
	static String TWITTER_CONSUMER_KEY = "LsCQaPOwd8k7WkyRFRZF4Q";
	static String TWITTER_CONSUMER_SECRET = "KJbJu5IQrlwxW7Cwnax3mMzAc4j3n6Wd2dG125srgk";

	// Preference Constants
	static String PREFERENCE_NAME = "twitter_oauth";
	static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
	static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
	static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

	static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

	// Twitter oauth urls
	static final String URL_TWITTER_AUTH = "auth_url";
	static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
	static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

	// Login button
	Button btnLoginTwitter;
	// Update status button
	Button btnUpdateStatus;
	// Logout button
	Button btnLogoutTwitter;
	// EditText for update
	EditText txtUpdate;
	// lbl update
	TextView lblUpdate;
	TextView lblUserName;

	// Progress dialog
	ProgressDialog pDialog;

	// Twitter
	private static Twitter twitter;
	private static RequestToken requestToken;
	
	// Shared Preferences
	private static SharedPreferences mSharedPreferences;
	
	// Internet Connection detector
	private ConnectionDetector cd;
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}
		
		// Check if twitter keys are set
		if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
			// stop executing code by return
			return;
		}

		// All UI elements
		btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
		btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
		btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
		txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
		lblUpdate = (TextView) findViewById(R.id.lblUpdate);
		lblUserName = (TextView) findViewById(R.id.lblUserName);

		// Shared Preferences
		mSharedPreferences = getApplicationContext().getSharedPreferences(
				"MyPref", 0);

Login with Twitter Account

Login with twitter account in your android application involves following process.

First user asked to authenticate into your application using their twitter account.
Once user successfully logged into his twitter account we will receive his oauth token and oauth secret.
oauth token and oauth secret will be stored in android application shared preferences.
Whenever you need oauth tokens, you can read from shared preferences.
Once user clicks logout button we will delete oauth token & secret from shared prefrences

7. Open your main activity and write click event for login button.

> In click event i am calling loginToTwitter().
> Once the user logins into twitter he will be redirected to your android app again with oauth verifier.
> Using oauth verifier we do another request to get access token and access token secret.

		/**
		 * Twitter login button click event will call loginToTwitter() function
		 * */
		btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Call login twitter function
				loginToTwitter();
			}
		});

		/** This if conditions is tested once is
		 * redirected from twitter page. Parse the uri to get oAuth
		 * Verifier
		 * */
		if (!isTwitterLoggedInAlready()) {
			Uri uri = getIntent().getData();
			if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
				// oAuth verifier
				String verifier = uri
						.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

				try {
					// Get the access token
					AccessToken accessToken = twitter.getOAuthAccessToken(
							requestToken, verifier);

					// Shared Preferences
					Editor e = mSharedPreferences.edit();

					// After getting access token, access token secret
					// store them in application preferences
					e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
					e.putString(PREF_KEY_OAUTH_SECRET,
							accessToken.getTokenSecret());
					// Store login status - true
					e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
					e.commit(); // save changes

					Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

					// Hide login button
					btnLoginTwitter.setVisibility(View.GONE);

					// Show Update Twitter
					lblUpdate.setVisibility(View.VISIBLE);
					txtUpdate.setVisibility(View.VISIBLE);
					btnUpdateStatus.setVisibility(View.VISIBLE);
					btnLogoutTwitter.setVisibility(View.VISIBLE);
					
					// Getting user details from twitter
					// For now i am getting his name only
					long userID = accessToken.getUserId();
					User user = twitter.showUser(userID);
					String username = user.getName();
					
					// Displaying in xml ui
					lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
				} catch (Exception e) {
					// Check log for login errors
					Log.e("Twitter Login Error", "> " + e.getMessage());
				}
			}
		}

	}

and code for loginToTwitter() function is

/**
	 * Function to login twitter
	 * */
	private void loginToTwitter() {
		// Check if already logged in
		if (!isTwitterLoggedInAlready()) {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
			Configuration configuration = builder.build();
			
			TwitterFactory factory = new TwitterFactory(configuration);
			twitter = factory.getInstance();

			try {
				requestToken = twitter
						.getOAuthRequestToken(TWITTER_CALLBACK_URL);
				this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
						.parse(requestToken.getAuthenticationURL())));
			} catch (TwitterException e) {
				e.printStackTrace();
			}
		} else {
			// user already logged into twitter
			Toast.makeText(getApplicationContext(),
					"Already Logged into twitter", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Check user already logged in your application using twitter Login flag is
	 * fetched from Shared Preferences
	 * */
	private boolean isTwitterLoggedInAlready() {
		// return twitter login status from Shared Preferences
		return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
	}
android twitter login
android twitter login oauth
android twitter login get username

Update Twitter Status

8. Once you login with twitter account you can see interface to update the status. Open your main activity class write a click event for update status button.

> In the following code async thread updateTwitterStatus() is called on clicking update status button.

/**
		 * Button click event to Update Status, will call updateTwitterStatus()
		 * function
		 * */
		btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Call update status function
				// Get the status from EditText
				String status = txtUpdate.getText().toString();

				// Check for blank text
				if (status.trim().length() > 0) {
					// update status
					new updateTwitterStatus().execute(status);
				} else {
					// EditText is empty
					Toast.makeText(getApplicationContext(),
							"Please enter status message", Toast.LENGTH_SHORT)
							.show();
				}
			}
		});

and code for updateTwitterStatus() async task is

	/**
	 * Function to update status
	 * */
	class updateTwitterStatus extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Updating to twitter...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Places JSON
		 * */
		protected String doInBackground(String... args) {
			Log.d("Tweet Text", "> " + args[0]);
			String status = args[0];
			try {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
				builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
				
				// Access Token 
				String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
				// Access Token Secret
				String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
				
				AccessToken accessToken = new AccessToken(access_token, access_token_secret);
				Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
				
				// Update status
				twitter4j.Status response = twitter.updateStatus(status);
				
				Log.d("Status", "> " + response.getText());
			} catch (TwitterException e) {
				// Error in updating status
				Log.d("Twitter Update Error", e.getMessage());
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog and show
		 * the data in UI Always use runOnUiThread(new Runnable()) to update UI
		 * from background thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(),
							"Status tweeted successfully", Toast.LENGTH_SHORT)
							.show();
					// Clearing EditText field
					txtUpdate.setText("");
				}
			});
		}

	}
android twitter update status
andorid update twitter status

Logout from Twitter

9. Open your main activity and write a click event for logout button. Please remember this logout code won’t logout user from the twitter in the browser. It will just clear the access tokens from your application shared preferences.

		/**
		 * Button click event for logout from twitter
		 * */
		btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Call logout twitter function
				logoutFromTwitter();
			}
		});

and code for logoutFromTwitter() function is

	/**
	 * Function to logout from twitter
	 * It will just clear the application shared preferences
	 * */
	private void logoutFromTwitter() {
		// Clear the shared preferences
		Editor e = mSharedPreferences.edit();
		e.remove(PREF_KEY_OAUTH_TOKEN);
		e.remove(PREF_KEY_OAUTH_SECRET);
		e.remove(PREF_KEY_TWITTER_LOGIN);
		e.commit();

		// After this take the appropriate action
		// I am showing the hiding/showing buttons again
		// You might not needed this code
		btnLogoutTwitter.setVisibility(View.GONE);
		btnUpdateStatus.setVisibility(View.GONE);
		txtUpdate.setVisibility(View.GONE);
		lblUpdate.setVisibility(View.GONE);
		lblUserName.setText("");
		lblUserName.setVisibility(View.GONE);

		btnLoginTwitter.setVisibility(View.VISIBLE);
	}

Final Code:

Final code of MainActivity.java

package com.androidhive.twitterconnect;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	// Constants
	/**
	 * Register your here app https://dev.twitter.com/apps/new and get your
	 * consumer key and secret
	 * */
	static String TWITTER_CONSUMER_KEY = "LsCQaPOwd8k7WkyRFRZF4Q";
	static String TWITTER_CONSUMER_SECRET = "KJbJu5IQrlwxW7Cwnax3mMzAc4j3n6Wd2dG125srgk";

	// Preference Constants
	static String PREFERENCE_NAME = "twitter_oauth";
	static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
	static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
	static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

	static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

	// Twitter oauth urls
	static final String URL_TWITTER_AUTH = "auth_url";
	static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
	static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

	// Login button
	Button btnLoginTwitter;
	// Update status button
	Button btnUpdateStatus;
	// Logout button
	Button btnLogoutTwitter;
	// EditText for update
	EditText txtUpdate;
	// lbl update
	TextView lblUpdate;
	TextView lblUserName;

	// Progress dialog
	ProgressDialog pDialog;

	// Twitter
	private static Twitter twitter;
	private static RequestToken requestToken;
	
	// Shared Preferences
	private static SharedPreferences mSharedPreferences;
	
	// Internet Connection detector
	private ConnectionDetector cd;
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}
		
		// Check if twitter keys are set
		if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
			// stop executing code by return
			return;
		}

		// All UI elements
		btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
		btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
		btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
		txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
		lblUpdate = (TextView) findViewById(R.id.lblUpdate);
		lblUserName = (TextView) findViewById(R.id.lblUserName);

		// Shared Preferences
		mSharedPreferences = getApplicationContext().getSharedPreferences(
				"MyPref", 0);

		/**
		 * Twitter login button click event will call loginToTwitter() function
		 * */
		btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Call login twitter function
				loginToTwitter();
			}
		});

		/**
		 * Button click event to Update Status, will call updateTwitterStatus()
		 * function
		 * */
		btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Call update status function
				// Get the status from EditText
				String status = txtUpdate.getText().toString();

				// Check for blank text
				if (status.trim().length() > 0) {
					// update status
					new updateTwitterStatus().execute(status);
				} else {
					// EditText is empty
					Toast.makeText(getApplicationContext(),
							"Please enter status message", Toast.LENGTH_SHORT)
							.show();
				}
			}
		});

		/**
		 * Button click event for logout from twitter
		 * */
		btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Call logout twitter function
				logoutFromTwitter();
			}
		});

		/** This if conditions is tested once is
		 * redirected from twitter page. Parse the uri to get oAuth
		 * Verifier
		 * */
		if (!isTwitterLoggedInAlready()) {
			Uri uri = getIntent().getData();
			if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
				// oAuth verifier
				String verifier = uri
						.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

				try {
					// Get the access token
					AccessToken accessToken = twitter.getOAuthAccessToken(
							requestToken, verifier);

					// Shared Preferences
					Editor e = mSharedPreferences.edit();

					// After getting access token, access token secret
					// store them in application preferences
					e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
					e.putString(PREF_KEY_OAUTH_SECRET,
							accessToken.getTokenSecret());
					// Store login status - true
					e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
					e.commit(); // save changes

					Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

					// Hide login button
					btnLoginTwitter.setVisibility(View.GONE);

					// Show Update Twitter
					lblUpdate.setVisibility(View.VISIBLE);
					txtUpdate.setVisibility(View.VISIBLE);
					btnUpdateStatus.setVisibility(View.VISIBLE);
					btnLogoutTwitter.setVisibility(View.VISIBLE);
					
					// Getting user details from twitter
					// For now i am getting his name only
					long userID = accessToken.getUserId();
					User user = twitter.showUser(userID);
					String username = user.getName();
					
					// Displaying in xml ui
					lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
				} catch (Exception e) {
					// Check log for login errors
					Log.e("Twitter Login Error", "> " + e.getMessage());
				}
			}
		}

	}

	/**
	 * Function to login twitter
	 * */
	private void loginToTwitter() {
		// Check if already logged in
		if (!isTwitterLoggedInAlready()) {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
			Configuration configuration = builder.build();
			
			TwitterFactory factory = new TwitterFactory(configuration);
			twitter = factory.getInstance();

			try {
				requestToken = twitter
						.getOAuthRequestToken(TWITTER_CALLBACK_URL);
				this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
						.parse(requestToken.getAuthenticationURL())));
			} catch (TwitterException e) {
				e.printStackTrace();
			}
		} else {
			// user already logged into twitter
			Toast.makeText(getApplicationContext(),
					"Already Logged into twitter", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Function to update status
	 * */
	class updateTwitterStatus extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Updating to twitter...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Places JSON
		 * */
		protected String doInBackground(String... args) {
			Log.d("Tweet Text", "> " + args[0]);
			String status = args[0];
			try {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
				builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
				
				// Access Token 
				String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
				// Access Token Secret
				String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
				
				AccessToken accessToken = new AccessToken(access_token, access_token_secret);
				Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
				
				// Update status
				twitter4j.Status response = twitter.updateStatus(status);
				
				Log.d("Status", "> " + response.getText());
			} catch (TwitterException e) {
				// Error in updating status
				Log.d("Twitter Update Error", e.getMessage());
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog and show
		 * the data in UI Always use runOnUiThread(new Runnable()) to update UI
		 * from background thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(),
							"Status tweeted successfully", Toast.LENGTH_SHORT)
							.show();
					// Clearing EditText field
					txtUpdate.setText("");
				}
			});
		}

	}

	/**
	 * Function to logout from twitter
	 * It will just clear the application shared preferences
	 * */
	private void logoutFromTwitter() {
		// Clear the shared preferences
		Editor e = mSharedPreferences.edit();
		e.remove(PREF_KEY_OAUTH_TOKEN);
		e.remove(PREF_KEY_OAUTH_SECRET);
		e.remove(PREF_KEY_TWITTER_LOGIN);
		e.commit();

		// After this take the appropriate action
		// I am showing the hiding/showing buttons again
		// You might not needed this code
		btnLogoutTwitter.setVisibility(View.GONE);
		btnUpdateStatus.setVisibility(View.GONE);
		txtUpdate.setVisibility(View.GONE);
		lblUpdate.setVisibility(View.GONE);
		lblUserName.setText("");
		lblUserName.setVisibility(View.GONE);

		btnLoginTwitter.setVisibility(View.VISIBLE);
	}

	/**
	 * Check user already logged in your application using twitter Login flag is
	 * fetched from Shared Preferences
	 * */
	private boolean isTwitterLoggedInAlready() {
		// return twitter login status from Shared Preferences
		return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
	}

	protected void onResume() {
		super.onResume();
	}

}
This image is for thumbnail purpose
android twitter connect
Subscribe
Notify of
guest
273 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
mangesh kaduskar
mangesh kaduskar
8 years ago

try to use twitter4j 3.0 in your project. it works for me

mangesh kaduskar
mangesh kaduskar
8 years ago

hi Ravi,

just because of ur tutorial i solved my lots of programming problems so thanks to u.

but i suggest you some changes.

1. when i login and visible buttons and textbox at that time if i click on back button it goes to twitter login page.

can you implement startActivityForResult method in your program.

2. AsyncTask should be implement in this example for login.

3. Get data from twitter in main thread cause network on main thread exception.

aaron@wiredd.in
8 years ago

there is no request token for this page

Navdeep Agrawal
Navdeep Agrawal
8 years ago

still my status can’t twit on twitter although I got success toast on click of tweet button

Guest
Guest
8 years ago

Hey,

Ive done everything you said in the tutorial. However, after i enter my username & password the following happens:

1)

The webpage at oauth://t4jsample?oauth_token=OSbp3U1QZh0DzCnDagbyf7mMtxzunjL1PO76KCgwwE&oauth_verifier=QuB89J1So4V4IrtOdcTa6poQ133S86BQwyprbDLsQ might be down or moved to another address..

2)

I get the following error in the logcat:

ERROR/Tab(375): onReceivedError -10 oauth://t4jsample?oauth_token=OSbp3U1QZh0DzCnDagbyf7mMtxzunjL1PO76KCgwwE&oauth_verifier=QuB89J1So4V4IrtOdcTa6poQ133S86BQwyprbDLsQ The protocol is not supported.

ANY HELP PLZZZZZZZ

Gemei
Gemei
8 years ago

You will have to write this code in your twitter login activity in the mainifest >>>

————————————————————————
Now you will get the intent from the browser and uri wouldn’t return null anymore 🙂

Rocky
Rocky
8 years ago
Reply to  Gemei

Didn’t work. Any other suggesions?

Jaison
Jaison
7 years ago
Reply to  Rocky

did u find the solution for this issue …..
Now i met the problem for couple of days i tried to find the solution …but my tries became failed

Marius
Marius
8 years ago

I get a null point for AccesToken (i can’t understand why)

i used this example and more others ()

E/Twitter Login Error(10411): > null
I used :
MainActivity.this.accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);

and
accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);

Twinkle
Twinkle
7 years ago
Reply to  Marius

I get the same situation.. did you get solution?

John
John
7 years ago
Reply to  Marius

Same here as well. Any solution for this?

Paky
Paky
7 years ago
Reply to  Marius

PUT
” MainActivity.this.accessToken = twitter.getOAuthAccessToken(requestToken, verifier);”

in a AsyncTask

alex
alex
8 years ago

Appropriate Callback URL for android app?

Nidhi Gupta
Nidhi Gupta
8 years ago

hi.. i am using twitter4j to make android twitter linked app.. i am facing a problem in login.. in my app i used a login button,after successful login i want the second activity should open.. but everytime after logging in,the first activity opens showing login button again and again, i have used this code.. package com.twitter_demo_project;

import oauth.signpost.OAuthConsumer;

import oauth.signpost.OAuthProvider;

import twitter4j.Twitter;

import twitter4j.TwitterException;

import twitter4j.TwitterFactory;

import twitter4j.User;

import twitter4j.auth.AccessToken;

import twitter4j.auth.RequestToken;

import twitter4j.conf.Configuration;

import twitter4j.conf.ConfigurationBuilder;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.app.ProgressDialog;

import android.content.Intent;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.content.pm.ActivityInfo;

import android.net.Uri;

import android.os.Build;

import android.os.Bundle;

import android.os.StrictMode;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

import android.widget.Toast;

@SuppressLint(“NewApi”)

public class TwitterLoginActivity extends Activity {

TextView tv;

Button loginBtn;

private OAuthConsumer consumer;

private OAuthProvider provider;

private ConnectionDetector cd;

Twitter twitter;

ProgressDialog pDialog;

private static SharedPreferences mSharedPreferences;

AlertDialogManager alert = new AlertDialogManager();

RequestToken requestToken;

private static final String CONSUMER_KEY = “********************”;

private static final String CONSUMER_SECRET = “****************”;

static String PREFERENCE_NAME = “twitter_oauth”;

static final String PREF_KEY_OAUTH_TOKEN = “oauth_token”;

static final String PREF_KEY_OAUTH_SECRET = “oauth_token_secret”;

static final String PREF_KEY_TWITTER_LOGIN = “isTwitterLogedIn”;

// static final String TWITTER_CALLBACK_URL = “oauth://t4jsample”;

static final String URL_TWITTER_AUTH = “auth_url”;

static final String URL_TWITTER_OAUTH_VERIFIER = “oauth_verifier”;

static final String URL_TWITTER_OAUTH_TOKEN = “oauth_token”;

public static final String OAUTH_CALLBACK_SCHEME = “x-oauthflow-twitter”;

public static final String OAUTH_CALLBACK_HOST = “callback”;

public static final String TWITTER_CALLBACK_URL = OAUTH_CALLBACK_SCHEME

+ “://” + OAUTH_CALLBACK_HOST;

/*

* public void storeAccessToken(AccessToken aToken) { SharedPreferences.Editor

* editor = mSharedPreferences.edit(); editor.putString(PREF_KEY_OAUTH_TOKEN,

* aToken.getToken()); editor.putString(PREF_KEY_OAUTH_SECRET,

* aToken.getTokenSecret()); editor.commit(); }

*/

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

setContentView(R.layout.twitter_login);

super.onCreate(savedInstanceState);

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

if (android.os.Build.VERSION.SDK_INT > 9) {

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

.permitAll().build();

StrictMode.setThreadPolicy(policy);

}

cd = new ConnectionDetector(getApplicationContext());

if (!cd.isConnectingToInternet()) {

alert.showAlertDialog(TwitterLoginActivity.this,

“Internet Connection Error”,

“Please connect to working Internet connection”, false);

return;

}

if (CONSUMER_KEY.trim().length() == 0

|| CONSUMER_SECRET.trim().length() == 0) {

// Internet Connection is not present

alert.showAlertDialog(TwitterLoginActivity.this, “Twitter oAuth tokens”,

“Please set your twitter oauth tokens first!”, false);

// stop executing code by return

return;

}

tv = (TextView) findViewById(R.id.welcome_txt);

loginBtn = (Button) findViewById(R.id.login_btn);

mSharedPreferences = getApplicationContext().getSharedPreferences(“MyPref”,

0);

loginBtn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

Thread th = new Thread(new Runnable() {

public void run() {

loginToTwitter();

}

});

th.start();

}

});

if (!isTwitterLoggedInAlready()) {

Uri uri = getIntent().getData();

if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {

// oAuth verifier

String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

try {

AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,

verifier);

Editor e = mSharedPreferences.edit();

e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());

e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());

// Store login status – true

e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);

e.commit();

Log.e(“Twitter OAuth Token”, “> ” + accessToken.getToken());

}

catch (Exception e) {

// Check log for login errors

Log.e(“Twitter Login Error”, “> ” + e.getMessage());

}

}

}

}

public void loginToTwitter() {

if (!isTwitterLoggedInAlready()) {

ConfigurationBuilder builder = new ConfigurationBuilder();

builder.setOAuthConsumerKey(CONSUMER_KEY);

builder.setOAuthConsumerSecret(CONSUMER_SECRET);

Configuration configuration = builder.build();

TwitterFactory factory = new TwitterFactory(configuration);

twitter = factory.getInstance();

try {

requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);

this.startActivity(new Intent(Intent.ACTION_VIEW, Uri

.parse(requestToken.getAuthenticationURL())));

}

catch (TwitterException e) {

e.printStackTrace();

}

}

else {

Intent i = new Intent(TwitterLoginActivity.this, TweetsListActivity.class);

startActivity(i);

}

}

private boolean isTwitterLoggedInAlready() {

return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);

}

protected void onResume() {

super.onResume();

}

}

tomer
tomer
8 years ago

Hello, very nice post, thank you.

My problem is that after i log in the app redirects me to my main activity and not to the activity where i called loginToTwitter()

Because of that i dont get the AccessToken.

How can i solve it?

sand
sand
8 years ago

hey… nothing happens when i click Login With Twitter??? what do i do??

wishy
wishy
8 years ago

Ahan! Wonderful nice tutorial.
It helps me a lot. Could you also post something related to how to use twitter search API?

Do Huu Tien
Do Huu Tien
8 years ago

I built your app and it always return back the callback url page, not showing the app. How can I fix it?

Kristina Ferm
Kristina Ferm
8 years ago
Reply to  Do Huu Tien

Mine does that, too.. I’m not sure if I’ve got the wrong “TWITTER_CALLBACK_URL” or if it’s something else. Would greatly appreciate a solution..

Rocky
Rocky
8 years ago

Hey! I couldn’t figure it out yet. Can you help me?

Rocky
Rocky
8 years ago

Did you get it working?

abhay
abhay
8 years ago

same problem i am facing.. did you get any solution?

pratik parekh
pratik parekh
8 years ago

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

add this code in your main activity under setContetnView

Avinash
Avinash
8 years ago
Reply to  pratik parekh

Even i too getting same issue. and as u said added the above code under setContentView.

After adding am not able to import the StrictMode. What can i do now and please help me out.

Moonlike Moonlygirl
Moonlike Moonlygirl
8 years ago

How can i migrate to API v1.1. to this project.. Because when I post tweet i show “Status tweeted successfully”. But i did not see my tweet on twitter . so what shoul I do? please help mee

dedar
dedar
8 years ago

after login on twitter i donot redirect back to app…what is the solution of this problem

lokendra
lokendra
8 years ago

when i am executing my app for tweeter integration it is giving some exception ….plzz any body can resolve it….network main thread exception

Avinash
Avinash
8 years ago
Reply to  lokendra

Right, even i too got the same..

Plz update the below code under setContentView(.. MainActivity.java

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

it will resolve.

trfilmographer
trfilmographer
7 years ago
Reply to  Avinash

I tired this, but I am still getting “android.os.NetworkOnMainThreadException”

trfilmographer
trfilmographer
7 years ago
Reply to  trfilmographer

Ah, I got it working now without edits to your comment. THanks

harshad
harshad
8 years ago

@Moonlike Moonlygirl …you are getting this error mean you are’nt added this jar: twitter4j-core-3.0.3.jar

TechtaSyS Yazılım
TechtaSyS Yazılım
8 years ago

Hey guys… For this example i found the solution…
Here is what i’ve dont:

I downloaded the source code from top.
Opened project with existing code in eclipse.
Changed android version of project to 4.1.2 from project properties

Deleted old Twitter4J.jar from lib folder of the project and copied twitter4j-core-3.0.5.jar in lib folder

And… here is the best part u should add some code in ur MainActivity.java

Just change this;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

into this;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

It’ll say StrickMode didnt defined or sth else, just mouseover it and try import it from android.os

That’s all folks.

It worked well from me.. Tried every way on this example..
Now, im on gettin user info from twitter… I’ll share codes a.s.a.p.

Elvira Chrisanty
Elvira Chrisanty
8 years ago

Hi, i am wondering if you have shared the way to get user info from twitter as you mentioned in this comment. Mind to share it since I am working on it but not successful yet.. thanks!

Bea Q
Bea Q
1 year ago

Hi! Did you finally get the correct code? If it is, could you please share it? I have been trying everything but still not work😭 Thank you very much!

Guest777
Guest777
8 years ago

Nice Job!
Thank you, this helped me alot!!!

Daeniight
Daeniight
8 years ago

same with comments and question below. why twitter redirect me to login button again? and it’ll be the same when i repeated login

Gebriel13
Gebriel13
8 years ago

It is closing every time i click on Login botton. I am using source code and it doesnt working.

careful7j
careful7j
8 years ago

Everything in this example is just fine, except that twitter is not 1.1 api version, while code is based on 1.0 api and therefore doesnt work. Would be nice if someone fix this.

jay01
jay01
8 years ago

I’m getting nullpointeexception at AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier); please helo me with this

girish
girish
7 years ago

What if another user wants to log in to twitter using same phone. There it displays as invalid request token and doesnot go to the next page. Its annoying. Plz help.!!

Juliatzin
Juliatzin
7 years ago

I needed to put a CountDownLatch so that accessToken = twitter.getOAuthAccessToken(requestToken, verifier); executes first

Jofferson Ramirez Tiquez

Im getting these errors, can anyone expalin it? Thank you.

nullRelevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=10f5ada3 or
http://www.google.co.jp/search?q=dceba048
TwitterException{exceptionCode=[10f5ada3-dceba048 10f5ada3-dceba01e], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.6}

Jofferson Ramirez Tiquez

Im getting these errors, can someone explain what’s the problem? thanks 🙂

02-04 19:58:02.941: E/TOKEN(2807): nullRelevant discussions can be found on the Internet at:

02-04 19:58:02.941: E/TOKEN(2807): http://www.google.co.jp/search?q=10f5ada3 or

02-04 19:58:02.941: E/TOKEN(2807): http://www.google.co.jp/search?q=dceba048

02-04 19:58:02.941: E/TOKEN(2807): TwitterException{exceptionCode=[10f5ada3-dceba048 10f5ada3-dceba01e], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.6}

Kunal Sharma
Kunal Sharma
7 years ago

java.lang.NoClassDefFoundError: twitter4j.conf.ConfigurationBuilder any one having solution to this problem

Android developer
Android developer
7 years ago

While creating an application what is the significance of Callback URL? Does keeping this field empty make any difference?

Mgamerz
Mgamerz
7 years ago

If you don’t put a url there it thinks its a desktop and won’t return the data you want when you try to get the token.

Sandeep Armal
Sandeep Armal
7 years ago

Hi Ravi,

I don’t understand why you add oauth://t4jsample as a twitter callback. TWITTER_CALLBACK_URL = “oauth://t4jsample”. I tried to add my app name but didn’t get app bak on my screen

json001
json001
7 years ago
Reply to  Sandeep Armal

i got this working.. the key to return to your app lies in the manifest file. you assign the TWITTER_CALLBACK_URL to the activity you want to return to..

the part of the code you need to pay attention to is the android:host of the intent-filter..
just assign the intent-filter to the activity you want the twitter to return to..
also TWITTER_CALLBACK_URL and host shoulde be the same.. in this example its “t4jsample”

prasanna
prasanna
7 years ago
Reply to  json001

How do i assign TWITTER_CALLBACK_URL to the activity

Ayuchuco!
Ayuchuco!
7 years ago
Reply to  prasanna

In the AndroidManifest.xml file, put this intent filter inside the tag that corresponds to the activity you want to assign for. I’m pretty sure you have more intent filters declared inside each activity you use on your project, so that any one as example to how to put this intent filter inside it and avoid getting errors.

jem88
jem88
7 years ago
Reply to  Sandeep Armal

Lot of respect for this workaround, thanks dude! 😉

Samolo
Samolo
7 years ago

Do you have find a solution for this issue?

Jaison
Jaison
7 years ago
Reply to  Samolo

Anyone find a solution for this issue

Samolo
Samolo
7 years ago

Put the instruction in a new Thread works.

MOhammed
MOhammed
7 years ago

i tried to change it with more error .Plz . can you send the full source code to me .

thank you

$neha
$neha
7 years ago

I have error i.e No authentication changes found
how can I solve this

Govinda Chandra Pradhan
Govinda Chandra Pradhan
7 years ago

i have downloaded the source code and i am getting the error
“Unfortunately, android twitter connect has stopped” can any one help me
or mail me the working source code

[email protected] please …

Nico
Nico
7 years ago

I got that problem too.

sandy
sandy
7 years ago

03-19 09:24:00.328: E/AndroidRuntime(1481): FATAL EXCEPTION: main
03-19 09:24:00.328: E/AndroidRuntime(1481): android.os.NetworkOnMainThreadException
03-19 09:24:00.328: E/AndroidRuntime(1481): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
03-19 09:24:00.328: E/AndroidRuntime(1481): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
03-19 09:24:00.328: E/AndroidRuntime(1481): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
03-19 09:24:00.328: E/AndroidRuntime(1481): at java.net.InetAddress.getAllByName(InetAddress.java:214)
03-19 09:24:00.328: E/AndroidRuntime(1481): at libcore.net.http.HttpConnection.(HttpConnection.java:70)
03-19 09:24:00.328: E/AndroidRuntime(1481): at libcore.net.http.HttpConnection.(HttpConnection.java:50)
03-19 09:24:00.328: E/AndroidRuntime(1481): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)

getting this error please help

Ayuchuco!
Ayuchuco!
7 years ago
Reply to  sandy

It’s clear!!! It says “android.os.NetworkOnMainThreadException”; that means that all Internet calls, Server calls, anyway…. all calls you make to the web, must be on another thread!!! This calls cannot be done on the main thread

Slim Ben Abdelwahed
Slim Ben Abdelwahed
7 years ago
Reply to  Ayuchuco!

what is the solution

Ankur Goyal
Ankur Goyal
7 years ago

03-21 02:08:32.725: E/AndroidRuntime(847): FATAL EXCEPTION: main

03-21 02:08:32.725: E/AndroidRuntime(847): Process: com.example.updatewht, PID: 847

03-21 02:08:32.725: E/AndroidRuntime(847): android.os.NetworkOnMainThreadException

03-21 02:08:32.725: E/AndroidRuntime(847): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)

03-21 02:08:32.725: E/AndroidRuntime(847): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)

03-21 02:08:32.725: E/AndroidRuntime(847): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)

03-21 02:08:32.725: E/AndroidRuntime(847): at java.net.InetAddress.getAllByName(InetAddress.java:214)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:254)

03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:137)

03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.HttpClientBase.request(HttpClientBase.java:53)

03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.HttpClientBase.post(HttpClientBase.java:82)

03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:116)

03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:98)

03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:287)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.example.updatewht.MainActivity.loginToTwitter(MainActivity.java:185)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.example.updatewht.MainActivity.access$1(MainActivity.java:171)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.example.updatewht.MainActivity$1.onClick(MainActivity.java:98)

03-21 02:08:32.725: E/AndroidRuntime(847): at android.view.View.performClick(View.java:4438)

03-21 02:08:32.725: E/AndroidRuntime(847): at android.view.View$PerformClick.run(View.java:18422)

03-21 02:08:32.725: E/AndroidRuntime(847): at android.os.Handler.handleCallback(Handler.java:733)

03-21 02:08:32.725: E/AndroidRuntime(847): at android.os.Handler.dispatchMessage(Handler.java:95)

03-21 02:08:32.725: E/AndroidRuntime(847): at android.os.Looper.loop(Looper.java:136)

03-21 02:08:32.725: E/AndroidRuntime(847): at android.app.ActivityThread.main(ActivityThread.java:5017)

03-21 02:08:32.725: E/AndroidRuntime(847): at java.lang.reflect.Method.invokeNative(Native Method)

03-21 02:08:32.725: E/AndroidRuntime(847): at java.lang.reflect.Method.invoke(Method.java:515)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

03-21 02:08:32.725: E/AndroidRuntime(847): at dalvik.system.NativeStart.main(Native Method)

I got that bug….how can i resolve this bug….anyone can help me please

khoahihi
khoahihi
7 years ago

I get Problem. when app execute then occur twitterexception message is : SSL handshake aborted: ssl=0x9805280: Failure in SSL library, usually a protocol error and error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:683 0x80a40440:0x00000000). This Exception appear when execute command requestToken=twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL); i do’nt understand reason. Please help me resolve this problem! Thanks

Twinkle
Twinkle
7 years ago
Reply to  khoahihi

update the twitter4j library to latest update , this will solve this problem

sathish
sathish
7 years ago

this application is woring fine when i login the and update status it is not showing any thing just your message sent like thaat

Guest
Guest
7 years ago

thanks for this tutor.
i downloaded ur source code, but i get much error on mainActivity.java
error on line :

package com.androidhive.twitterconnect;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

and much more, can u help me to solve my problem? please

Ayuchuco!
Ayuchuco!
7 years ago
Reply to  Guest

If you’re creating a project in Eclipse from a blank one and you are also copying only the files mentioned in this tutorial, yo should change the first line that reads “package com.androidhive.twitterconnect;” for the actual package you configured and where this class is

Anas Azeem
Anas Azeem
7 years ago

After authenticating the app open the activity on Chrome. “How in the world can a browser open an Android ACTIVITY”???
Can any wise person tell me how to redirect the app back to the “Android App (not the browser)”. I’ve tried using the

android:launchMode=”singleTask”. Using this the control do return to the app, but all tokens and usernames which were were visible in the logcat before are not visible now.

Mgamerz
Mgamerz
7 years ago
Reply to  Anas Azeem

The intent filter will catch the new link it’s trying to direct you to and it contains information the app is supposed to catch.

Syed Talha
Syed Talha
7 years ago

Can you please provide the proper Twitter logout

Dinesh Kumar A
Dinesh Kumar A
7 years ago

1.In my app contains twitter integration and I follow this code(class files (Not Download)) and i have error an while taping the Login Button Nothing was Happened.. Plz tell some Solution.

2.When i download the Code , how to change a authorize app view in while opening the Dialog window

cnpisit
cnpisit
7 years ago

i already for this tutorial but i still can’t get requestToken after login with twitter. i use twitter4j-core-4.0.1.jar library

Paula
Paula
7 years ago

Thanks for the tutorial, but when I click in the Login Button Nothing Happened. If someone knows how to fix this, I’d be very grateful. Thanks!

Bea Q
Bea Q
1 year ago
Reply to  Paula

Hi! Did you finally get the correct code? If it is, could you please share it? I have been trying everything but still not work😭Thank you very much

273
0
Would love your thoughts, please comment.x
()
x