Build Android applications with Twitter


#1

I am building Android applications with Twitter following SAMS book Twitter API in 24 hours using OAuth. The code compiled OK. When I ran the application and clicked the “Authenticate” button, I got the message “Unfortunately, TwitterOauth has stopped.”

Please help, thanks. The code is listed below:

package com.example.twitteroauth;

import java.sql.Date;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
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;

/**

  • Using Twitter4J Java library and Signpost OAuth library to access Twitter
    */
    public class TwitterOauth extends Activity {

    private static final String APP = “TWITTEROAUTH”;

    private Twitter twitter;
    private OAuthProvider provider;
    private OAuthConsumer consumer;

    private String CONSUMER_KEY = “v7xwr2xFzDEsgDvg962Paw”;
    private String CONSUMER_SECRET = “XXXXX”;
    private String CALLBACK_URL = “myapp://twitteroauth”;

    private TextView tweetTextView;
    private Button buttonLogin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tweetTextView = (TextView)findViewById(R.id.tweet);
    buttonLogin = (Button)findViewById(R.id.ButtonLogin);
    buttonLogin.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    askOAuth();
    }
    });
    }

    /**

    • Direct to Twitter to authenticate the user
      */
      private void askOAuth() {
      try {
      // Use Apache HttpClient for HTTP messaging
      consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
      provider = new CommonsHttpOAuthProvider(“https://api.twitter.com/oauth/request_token”,
      https://api.twitter.com/oauth/access_token”,
      https://api.twitter.com/oauth/authorize”);
      String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
      Toast.makeText(this, “Authorize this app!”, Toast.LENGTH_LONG).show();
      this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
      } catch (Exception e) {
      Log.e(APP, e.getMessage());
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      }
      }

    /**

    • Get the verifier from the callback URL.

    • Retrieve token and token_secret.

    • Feed them to twitter4j along with consumer key and secret
      */
      @Override
      protected void onNewIntent(Intent intent) {

      super.onNewIntent(intent);

      Uri uri = intent.getData();
      if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {

       String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
      
       try {
       	// Populate token and token_secret in consumer
       	provider.retrieveAccessToken(consumer, verifier);
       	
       	// TODO: you might want to store token and token_secret in you app settings!
       	AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
       	
       	// Initialize Twitter4J
       	ConfigurationBuilder confbuilder  = new ConfigurationBuilder();
       	confbuilder.setOAuthAccessToken(a.getToken()) 
       		.setOAuthAccessTokenSecret(a.getTokenSecret()) 
       		.setOAuthConsumerKey(CONSUMER_KEY) 
       		.setOAuthConsumerSecret(CONSUMER_SECRET);
       	twitter = new TwitterFactory(confbuilder.build()).getInstance();
       		
       	// Create a tweet
       	Date d = new Date(System.currentTimeMillis());
       	String tweet = "Twitter API 24 HRS: TwitterOAuth works on Android " + d.toLocaleString();
      
       	// Post the tweet
       	twitter.updateStatus(tweet);
       	
       	// Show message
       	tweetTextView.setText(tweet);
       	Toast.makeText(this, tweet, Toast.LENGTH_LONG).show();
       	buttonLogin.setVisibility(Button.GONE);
       	
       } catch (Exception e) {
       	Log.e(APP, e.getMessage());
       	Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
       }
      

      }
      }
      }

My Twitter Settings:

OAuth settings

Your application’s OAuth settings. Keep the “Consumer secret” a secret. This key should never be human-readable in your application.

Access level

Read and write

About the application permission model

Consumer key

D7TJHxRHhTesKExt1zEcg

Consumer secret

XXXXXXXX

Request token URL

https://api.twitter.com/oauth/request_token

Authorize URL

https://api.twitter.com/oauth/authorize

Access token URL

https://api.twitter.com/oauth/access_token

Callback URL

None

Access:

Read only

Read and Write

Read, Write and Access direct messages

I tried all 3 Access types, all are not working, got the same message “Unfortunately, TwitterOauth has stopped.”. I also set the date and time to Pacific Daytime in the Android Virtual Device. What do I miss? Thanks in advance.


#2

set call back URl in application setting,i fixed this issue on emulator but on device again i am facing same issue.


#3

callback URL: http://www.google.com

public class AuthActivity extends Activity {

private Twitter twitter;
private OAuthProvider provider;
private CommonsHttpOAuthConsumer consumer;

private String CONSUMER_KEY =           Constants.CONSUMER_KEY;
private String CONSUMER_SECRET =        Constants.CONSUMER_SECRET;
private String CALLBACK_URL =          "callback://tweeter";

private ImageButton buttonLogin;

@Override
public void onCreate(Bundle savedInstanceState) {
	System.setProperty("http.keepAlive", "false");
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main_oauth);
	System.out.println("Check 1");
	//check for saved log in details..
     checkForSavedLogin();

	//set consumer and provider on teh Application service
	getConsumerProvider();
	System.out.println("Check 2");
	//Define login button and listener
	buttonLogin = (ImageButton)findViewById(R.id.ButtonLogin);
	buttonLogin.setOnClickListener(new OnClickListener() {  
		public void onClick(View v) {
			askOAuth(); 
		}
	});  
}

private void checkForSavedLogin() {
	// Get Access Token and persist it
	AccessToken a = getAccessToken();
	if (a!=null) 
	{System.out.println("Check state: "+ a);
	return;	//if there are no credentials stored then return to usual activity
	}
	// initialize Twitter4J
	System.out.println("Check state2: "+a);
	twitter = new TwitterFactory().getInstance();
	twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
	twitter.setOAuthAccessToken(a);
	((TwitterApplication)getApplication()).setTwitter(twitter);
	//((TwitterApplication)getApplication()).setConsumer(consumer);
	startFirstActivity();
	finish();
}

/**
 * Kick off the activity to display 
 */
private void startFirstActivity() {		
	System.out.println("STARTING FIRST ACTIVITY!");
	//Intent i = new Intent(this, TweetsActivity.class);
	Intent i = new Intent(this, Tab.class);
	//Intent i = new Intent(this, sendMessage.class);
	startActivityForResult(i, Constants.ACTIVITY_LATEST_TWEETS);
}

/**
 * This method checks the shared prefs to see if we have persisted a user token/secret
 * if it has then it logs on using them, otherwise return null
 * 
 * @return AccessToken from persisted prefs
 */
private AccessToken getAccessToken() {
	SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
	String token = settings.getString("accessTokenToken", "");
	String tokenSecret = settings.getString("accessTokenSecret", "");
	if (token!=null && tokenSecret!=null && !"".equals(tokenSecret) && !"".equals(token)){
		return new AccessToken(token, tokenSecret);
	}
	return null;
}	

/**
 * Open the browser and asks the user to authorize the app.
 * Afterwards, we redirect the user back here!
 */
private void askOAuth() {
	try {
		System.out.println("Check 3");
		consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
		provider = new DefaultOAuthProvider("https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", "https://api.twitter.com/oauth/authorize");
		String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
		Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
		System.out.println("fff "+consumer);
		System.out.println("ffff "+provider);
		setConsumerProvider();
		
		System.out.println("fff 1"+consumer);
		System.out.println("ffff 1"+provider);

// consumer=null;
// provider=null;

		//startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
		WebView w=new WebView(this);
		w.requestFocus(View.FOCUS_DOWN);
		w.loadUrl(authUrl);
		setContentView(w);
		
		
	} catch (Exception e) {
		Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
	}
}


/**
 * As soon as the user successfully authorized the app, we are notified
 * here. Now we need to get the verifier from the callback URL, retrieve
 * token and token_secret and feed them to twitter4j (as well as
 * consumer key and secret).
 */
@Override
protected void onResume() {
	super.onResume();
	System.out.println("RESUMING!!");
	if (this.getIntent()!=null && this.getIntent().getData()!=null){
		Uri uri = this.getIntent().getData();
		if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
			String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
			try {
				// this will populate token and token_secret in consumer
				provider.retrieveAccessToken(consumer, verifier);

				// Get Access Token and persist it
				AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
				storeAccessToken(a);

				// initialize Twitter4J
				twitter = new TwitterFactory().getInstance();
				twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
				twitter.setOAuthAccessToken(a);
				((TwitterApplication)getApplication()).setTwitter(twitter);
				//Log.e("Login", "Twitter Initialised");
				
				startFirstActivity();
				

			} catch (Exception e) {
				//Log.e(APP, e.getMessage());
				e.printStackTrace();
				
				System.out.println("I m here....");
				consumer=null;
				provider=null;
				
				Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
				//finish();
				android.os.Process.killProcess(android.os.Process.myPid());
			}
		}
	}
}

/**
 * This method persists the Access Token information so that a user
 * is not required to re-login every time the app is used
 * 
 * @param a - the access token
 */
private void storeAccessToken(AccessToken a) {
	SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
	SharedPreferences.Editor editor = settings.edit();
	editor.putString("accessTokenToken", a.getToken());
	editor.putString("accessTokenSecret", a.getTokenSecret());
	editor.commit();
}	
/**
 * Get the consumer and provider from the application service (in the case that the
 * activity is restarted so the objects are not lost
 */
private void getConsumerProvider() {
	OAuthProvider p = ((TwitterApplication)getApplication()).getProvider();
	System.out.println("get:"+p);
	if (p!=null){
		provider = p;
		System.out.println("getnot:"+p);
	}
	CommonsHttpOAuthConsumer c = ((TwitterApplication)getApplication()).getConsumer();
	if (c!=null){
		consumer = c;
		System.out.println("getCOnsumer:"+c);
	}
}		
/**
 * Set the consumer and provider from the application service (in the case that the
 * activity is restarted so the objects are not lost)
 */
private void setConsumerProvider() {
	if (provider!=null){
		System.out.println("yyyy"+provider);
		((TwitterApplication)getApplication()).setProvider(provider);
	}
	if (consumer!=null){
		System.out.println("yy");
		((TwitterApplication)getApplication()).setConsumer(consumer);
	}
}	

}


#4

Use this code…

import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TwitterActivity extends Activity {

private String consumerKey="U68MHs8ttq7yc7XwjHcYA";
private String consumerSecret="JIzuJDI3PYZmY5juW5rdKXAfBZusYJuWfkQz2sTzQc";
private RequestToken rToken;
public String TAG="inApplication";
public String CALLBACK_URL="Twitter";
public Twitter twitter;
private Button loginButton;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.main);
    this.loginButton=(Button) this.findViewById(R.id.button1);
    this.loginButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          	try {
				loginButtonClick();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
      });                
}

public void loginButtonClick() throws ClientProtocolException, IOException, JSONException{
	 twitter = new TwitterFactory().getInstance();
     try
     {
     twitter.setOAuthConsumer(consumerKey, consumerSecret);
     String callbackURL = "Twitter://host";
     //AccessToken at = new AccessToken(accessToken, accessSecret);
     //twitter.setOAuthAccessToken(at);
      rToken= twitter.getOAuthRequestToken(callbackURL);
     startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(rToken.getAuthenticationURL())));
     }
     catch(IllegalStateException e)
     {
    // access token is already available, or consumer key/secret is not set.
        if(!twitter.getAuthorization().isEnabled()){
	        System.out.println("OAuth consumer key/secret is not set.");
	        System.exit(-1);
        }
        e.printStackTrace();
     }
     catch(Exception e)
     {
     Toast.makeText(getApplicationContext(), "Network Host not responding",Toast.LENGTH_SHORT).show();
     e.printStackTrace();
     }
	
	
}

@Override
protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.i(TAG, "New Intent Arrived");
        Uri uri = intent.getData();
        if (uri != null && uri.toString().startsWith(CALLBACK_URL)) { // If the user has just logged in
                String oauthVerifier = uri.getQueryParameter("oauth_verifier");
                Log.i(TAG,  oauthVerifier);
                AccessToken at=null;
				try {
					at = twitter.getOAuthAccessToken(rToken, oauthVerifier);
				} catch (TwitterException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                twitter.setOAuthAccessToken(at);
                /*try {
					twitter.updateStatus("Testing my first ever android app!");
				} catch (TwitterException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
                //authoriseNewUser(oauthVerifier);
                Intent i = new Intent(this,LoginScreen.class); 
                i.putExtra("twitter", twitter);
                startActivity(i);  
        }
      
}

@Override
protected void onResume() {
        super.onResume();
        Log.i(TAG, "Arrived at onResume");
}

}


#5

I am getting the same error.but not able to solve it.kindly guide me
thank you


#6

i am also getting same problem . please help me thank you.


#7

Did you attached the jar file using build path. if added already, check whether its enabled or checked in order and export. unless you check that, library will not get attached to the application.


#8

Hello.
I’m busy with a simple app just to display tweets using a certain hashtag in Android, example #happy. How can I do this without having the user to login to twitter? I have created my app on twitter.dev, but now I’m stuck


#9

potay.com


#10

Hello,
twitter.getOAuthRequestToken(URL_CALL_BACK);
giving an error, Do you know the reason