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.
 
//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();
}
@Override
}
Your Android.mainfest.xml file should looks like this.
</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.
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;
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
*/
*
* 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.
*/
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.
*/
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);
@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)) {
//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();
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();
// 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);
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();
}
}
}
*/
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
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!!!!!!!!
// TODO: you might want to store token and token_secret in you app settings!!!!!!!!
AccessToken a =
new AccessToken(httpOauthConsumer.getToken(), httpOauthConsumer.getTokenSecret());
// initialize Twitter4J
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
twitter.setOAuthAccessToken(a);
// create a tweet
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
String tweet = "#OAuth working! " + d.toLocaleString();
// send the tweet
twitter.updateStatus(tweet);
// feedback for the user...
// 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();
}
}
}
 
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();
}
}
Toast.makeText(this, tweet, Toast.LENGTH_LONG).show();
buttonLogin.setVisibility(Button.GONE);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
 
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"
<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.
