Twitter4j OAuth on Android is Simple...


Last Updated:

  1. Mukesh

    Mukesh New Member This Topic's Starter

    Joined:
    Nov 15, 2010
    Messages:
    1
    Likes Received:
    0
    Hi All,

    Twitter4j OAuth for Android example by Mukesh,this example would help you to understand the usage of Intent after succesfully authentication.
    make use of it and enjoy..

    About : OAuth

    OAuth is an open protocol that allows users to hand out tokens instead of usernames and passwords to their data hosted by a given service provider. With Twitter finally deciding to deprecate the existing Basic Authentication by June, most of the apps would have to implement OAuth for Twitter.

    While implementing OAuth for Twitter on Android platform, I came across hell of out of tutorials and blogs, some might gives different ways of using OAuth. below is the example where i have tried the easiest way to implement Twitter4j and the challenges you may face.

    Step 1:

    First step for creating the solution is registering an app with Twitter. You can do that by filling in details at this URL: Twitter.

    Some basic info like Application icon, App name etc are needed.

    The two most important details to be provided are, type of Application and Callback URL. Select type of application as "Browser".

    Now callback url could be any valid url.

    Default Action should be : Select as "Read and Write"

    Once you successfully fill up all the details, you would get "Consumer Key" and "Consumer Secret" from Twitter. These are the keys Twitter uses for identifying your app so note it down carefully.

    Step 2:
    Download signpost-commonshttp4-1.2.jar , signpost-core-1.2.jar, twitter4j-core-2.1.0.jar file and add your project libs.
    I'm using "signpost-commonshttp4" and "signpost-core" open-source libraries for implementation.

    Step3: Create a Android Application, Add the above downloaded jar files into your projects, add internet permissions to your project manifest file.


    Below is the code which can be reuse.


    package​
    com.sogeti.msl;

     
     

    import​
    java.sql.Date;

     

    import​
    oauth.signpost.OAuthProvider;

    import​
    oauth.signpost.basic.DefaultOAuthProvider;

    import​
    oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

    import​
    android.app.Activity;

    import​
    android.content.Intent;

    import​
    android.net.Uri;

    import​
    android.os.Bundle;

    import​
    android.util.Log;

    import​
    android.widget.Toast;

     

    import​
    twitter4j.Twitter;

    import​
    twitter4j.TwitterFactory;

    import​
    twitter4j.http.AccessToken;

    import​
    android.widget.Button;

    import​
    android.widget.TextView;

    import​
    com.sogeti.msl.R;

     
     

    public​
    class OAuthForTwitter extends Activity {

    private CommonsHttpOAuthConsumer httpOauthConsumer;
    private OAuthProvider httpOauthprovider;
    public final static String consumerKey = "sdOjEI2cOxzTLHMCCMmuQ";
    public final static String consumerSecret = "biI3oxIBX2QMzUIVaW1wVAXygbynuS80pqSliSDTc";
    private final String CALLBACKURL = "myapp://mainactivity";
    private Twitter twitter;
    private TextView tweetTextView;
    private Button buttonLogin;

    // static Twitter jtwit;

    /*
    *
    * OnCreate method for class
    */

    @Override

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tweetTextView = (TextView)findViewById(R.id.tweet);
    buttonLogin = (Button)findViewById(R.id.ButtonLogin);

    setContentView(R.layout.
    main);
    doOauth();
    }
    /**
    * Opens the browser using signpost jar with application specific
    * consumerkey and consumerSecret.
    */

    private void doOauth() {
    try {
    httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
    httpOauthprovider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
    "http://twitter.com/oauth/access_token",
    "http://twitter.com/oauth/authorize");
    String authUrl =
    httpOauthprovider.retrieveRequestToken(httpOauthConsumer, CALLBACKURL);

    this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
    }
    catch (Exception e) {
    Toast.makeText(
    this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
    }
    /**
    * After use authorizes this is the function where we get back callbac with
    * user specific token and secret token. You might want to store this token
    * for future use.
    */


    /*
    @Override
    protected void onNewIntent(Intent intent) {

    super.onNewIntent(intent);

    Uri uri = intent.getData();
    //Check if you got NewIntent event due to Twitter Call back only
    if (uri != null && uri.toString().startsWith(CALLBACKURL)) {​
    String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
    Toast.makeText(this, verifier, Toast.LENGTH_LONG).show(); ​
    try {
    // this will populate token and token_secret in consumer
    httpOauthprovider.retrieveAccessToken(httpOauthConsumer, verifier);

    String userKey = httpOauthConsumer.getToken();
    String userSecret = httpOauthConsumer.getConsumerSecret();
    Toast.makeText(this, userKey, Toast.LENGTH_LONG).show();
    Toast.makeText(this, userSecret, Toast.LENGTH_LONG).show();

    AccessToken accessToken = new AccessToken(httpOauthConsumer.getToken(), httpOauthConsumer.getConsumerSecret());

    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);

    twitter.setOAuthAccessToken(accessToken);

    // create a tweet
    Date d = new Date(System.currentTimeMillis());
    String tweet = "#OAuth working! " + d.toLocaleString(); ​
    // send the tweet
    twitter.updateStatus(tweet); ​
    // feedback for the user... ​
    Toast.makeText(this, tweet, Toast.LENGTH_LONG).show(); ​

     ​

    //twitter.updateStatus("From My Android...");
    /*

    List<Status> statuses = twitter.getHomeTimeline();
    System.out.println("Friend Status Updates");
    for (Status status : statuses)
    {
    System.out.println(status.getUser().getName() + " said " + status.getText());
    Toast.makeText(this, status.getUser().getName() + " said " + status.getText(), Toast.LENGTH_LONG).show();

    }
    }
    catch(Exception e){
    Log.d("", e.getMessage());
    Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }

    }
    }

    */​


    @Override

    protected void onNewIntent(Intent intent) {

    super.onNewIntent(intent);

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

    String verifier = uri.getQueryParameter(oauth.signpost.OAuth.
    OAUTH_VERIFIER);

    try {
    // this will populate token and token_secret in consumer

    httpOauthprovider.retrieveAccessToken(httpOauthConsumer, verifier);

    // TODO: you might want to store token and token_secret in you app settings!!!!!!!!

    AccessToken a = ​
    new AccessToken(httpOauthConsumer.getToken(), httpOauthConsumer.getTokenSecret());

    // initialize Twitter4J

    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(a);

    // create a tweet

    Date d = ​
    new Date(System.currentTimeMillis());
    String tweet =
    "#OAuth working! " + d.toLocaleString();

    // send the tweet

    twitter.updateStatus(tweet);

    // feedback for the user...

    tweetTextView.setText(tweet);
    Toast.makeText(
    this, tweet, Toast.LENGTH_LONG).show();
    buttonLogin.setVisibility(Button.GONE);

    }
    catch (Exception e) {

    Toast.makeText(
    this, e.getMessage(), Toast.LENGTH_LONG).show();
    }

    }
    }

    &#12288;
    private void askOAuth() {
    try {
    httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
    httpOauthprovider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
    "http://twitter.com/oauth/access_token",
    "http://twitter.com/oauth/authorize");
    String authUrl =
    httpOauthprovider.retrieveRequestToken(httpOauthConsumer, CALLBACKURL);
    Toast.makeText(
    this, "Please authorize this app!", Toast.LENGTH_LONG).show();
    this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
    }
    catch (Exception e) {

    Toast.makeText(
    this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
    }

    }


    Your Android.mainfest.xml file should looks like this.

    <?​
    xml version="1.0" encoding="utf-8"?>
    <
    manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.sogeti.msl"

    android:versionCode="1"

    android:versionName="1.0">

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable = "true">

    <activity android:name=".OAuthForTwitter"

    android:label="@string/app_name" android:launchMode="singleInstance">

    <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="myapp" android:host="mainactivity" />

    </intent-filter>

    </activity>


    </application>

    <uses-sdk android:minSdkVersion="7" />

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

    </
    manifest>


    Common Errors:

    You may get the Userlogin/Password is incorrect, this is due to the wrong way of creating the ConsumerKey. log on to https://twitter.com/apps/new and get it corrected or create a new key.make sure you follow the above instuctions.

    Please get back to me for any furhter information.
     

    Advertisement
  2. Steven58

    Steven58 Reformed PH VIP Member

    Joined:
    Feb 19, 2010
    Messages:
    32,920
    Likes Received:
    25,271
    Welcome to Android Forums! Glad you signed up!

    This belongs in the DEV section. You may want to re-post there. :)
     
  3. Martimus

    Martimus One bite at a time... Moderator

    Joined:
    Jul 9, 2010
    Messages:
    19,535
    Likes Received:
    4,045
    Welcome to the Android Forums!
     
  4. bigdroid

    bigdroid Well-Known Member

    Joined:
    Oct 31, 2009
    Messages:
    7,112
    Likes Received:
    132
    Welcome to Android Forums!! :)
     
  5. Tsubas

    Tsubas New Member

    Joined:
    Jan 11, 2011
    Messages:
    1
    Likes Received:
    0
    Hi, i try this code and have a error in doAuth() exception
    "private void doOauth() {
    try {
    httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
    httpOauthprovider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
    "http://twitter.com/oauth/access_token",
    "http://twitter.com/oauth/authorize");
    String authUrl =
    httpOauthprovider.retrieveRequestToken(httpOauthConsumer, CALLBACKURL);

    this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
    }
    catch (Exception e) {
    Toast.makeText(
    this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
    }
    "

    Said that can communicate whit the service twitter.com, what i do wrong?? Is the way i register my app on twitter???
     
  6. sogwiz

    sogwiz New Member

    Joined:
    Feb 23, 2011
    Messages:
    1
    Likes Received:
    0
    Everything works fine until the callback. The callback doesn't redirect the user back to my app; instead, it stays in the browser with an error indicating it couldn't find the page.
    I'm using myapp://ouathactivity as the callback url. The error I see in logcat is the following:

    "02-22 19:26:16.415: ERROR/Tab(417): onReceivedError -10 myapp://oauthactivity?oauth_token=<XX>&oauth_verifier=<XX> The protocol is not supported."

    Any help here is appreciated
     
  7. karthikstone

    karthikstone New Member

    Joined:
    Jun 2, 2011
    Messages:
    2
    Likes Received:
    0


     
  8. karthikstone

    karthikstone New Member

    Joined:
    Jun 2, 2011
    Messages:
    2
    Likes Received:
    0
    i'm a bignner in android, i can all coding but i dono myapp//mainactivity

    can u tell me, what's meaning CALLBACKURL

    what should i give to mainactivity

    why u didn't call "askOAuth()" method
     
  9. Minorko

    Minorko New Member

    Joined:
    Sep 16, 2011
    Messages:
    1
    Likes Received:
    0
    How can I catch a successful event tweets on the wall?
     

Share This Page

Loading...