While developing one of my Android application, i found it was hard to find a good and simple tutorial on how to integrate Twitter into Android app. There are some external java libraries over the net that can be used to integrate Twitter into Android app, but they lack of good documentation and tutorial on how to use it on Android. So i made my own implementation using Twitter4j and oauth-signpost library. In this tutorial, i create one sample Android project to show how to connect to Twitter, save it’s token and username on shared preferences so it can be used later to post status to Twitter.
I. Register Twitter Application
To enable user to post status to Twitter, first you have to create one Twitter application. Simply go to Twitter Apps page and register your application. Fill the ‘Application Name‘ with your desired name, it has to be unique. If you use a name that already exist (taken by someone), you’ll get a warning message. On ‘Application Type’ option, choose ‘Browser’ , and because its a browser type application but used in mobile application, you can set it’s callback url on ‘Callback URL‘ field with any url you want. On ‘Default Access type’, choose ‘Read and Write‘ to enable access to post status. Click save and if all things going well, you’ll get a page showing your consumer key and secret key. Copy these two keys for later use in Android app.
II. Android Integration
To integrate Twitter into Android app, you need four external jar files from two different libraries, Twitter4j and oauth-signpost. You can download latest version from Twitter4j download page or use the one included in my sample project (twitter4j-core-2.1.6.jar) and oauth-signpost from oauth-signpost download page (signpost-core-1.2.1.1.jar, signpost-commonshttp4-1.2.1.1.jar, signpost-jetty6-1.2.1.1.jar). Add the four external jars into your Android project (on Eclipse, right click on your project->properties then on Java Build Path click Add External JARs button to select files)
In my sample project, i create three helper classes (TwitterApp.java, TwitterDialog.java, and TwitterSession.java) to handle authentication using Webview Dialog and session handler to save token and username on Shared Preferences.
Code implementation
1. Twitter Connection (TestConnection.java)
This example shows how to connect to Twitter, display webview dialog to authorize user then save user’s token and username on shared preference for later use.
public class TestConnect extends Activity {
private TwitterApp mTwitter;
private CheckBox mTwitterBtn;
private static final String twitter_consumer_key = "xxx";
private static final String twitter_secret_key = "xxx";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTwitterBtn = (CheckBox) findViewById(R.id.twitterCheck);
mTwitterBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onTwitterClick();
}
});
mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
mTwitter.setListener(mTwLoginDialogListener);
if (mTwitter.hasAccessToken()) {
mTwitterBtn.setChecked(true);
String username = mTwitter.getUsername();
username = (username.equals("")) ? "Unknown" : username;
mTwitterBtn.setText(" Twitter (" + username + ")");
mTwitterBtn.setTextColor(Color.WHITE);
}
Button goBtn = (Button) findViewById(R.id.button1);
goBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(TestConnect.this, TestPost.class));
}
});
}
private void onTwitterClick() {
if (mTwitter.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete current Twitter connection?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mTwitter.resetAccessToken();
mTwitterBtn.setChecked(false);
mTwitterBtn.setText(" Twitter (Not connected)");
mTwitterBtn.setTextColor(Color.GRAY);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
mTwitterBtn.setChecked(true);
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mTwitterBtn.setChecked(false);
mTwitter.authorize();
}
}
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
@Override
public void onComplete(String value) {
String username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
mTwitterBtn.setText(" Twitter (" + username + ")");
mTwitterBtn.setChecked(true);
mTwitterBtn.setTextColor(Color.WHITE);
Toast.makeText(TestConnect.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
}
@Override
public void onError(String value) {
mTwitterBtn.setChecked(false);
Toast.makeText(TestConnect.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
}
First, create an instance of TwiterApp class with context, consumer key and secret key as constructor’s parameters. Use hasAccessToken() method to check if there is previously saved session. If there is no saved session, call authorize() to open authorization dialog. If user allows the connection, his access token and user name will be saved on shared preferences. You can setup listener to handle on success and on error event by creating an instance of TwDialogListener and pass it to setListener() method.
2. Post Status (TestPost.java)
This example shows how to post Twitter status. If there is no previously saved session, display authorization dialog to allow user authorize the connection then post status using different thread.
public class TestPost extends Activity {
private TwitterApp mTwitter;
private CheckBox mTwitterBtn;
private String username = "";
private boolean postToTwitter = false;
private static final String twitter_consumer_key = "xxxx";
private static final String twitter_secret_key = "xxxx";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post);
Button postBtn = (Button) findViewById(R.id.button1);
final EditText reviewEdit = (EditText) findViewById(R.id.revieew);
postBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String review = reviewEdit.getText().toString();
if (review.equals("")) return;
postReview(review);
if (postToTwitter) postToTwitter(review);
}
});
mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
mTwitter.setListener(mTwLoginDialogListener);
mTwitterBtn = (CheckBox) findViewById(R.id.twitterCheck);
mTwitterBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mTwitter.hasAccessToken()) {
postToTwitter = mTwitterBtn.isChecked();
} else {
mTwitterBtn.setChecked(false);
mTwitter.authorize();
}
}
});
if (mTwitter.hasAccessToken()) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
mTwitterBtn.setText(" Twitter (" + username + ")");
}
}
private void postReview(String review) {
//post to server
Toast.makeText(this, "Review posted", Toast.LENGTH_SHORT).show();
}
private void postToTwitter(final String review) {
new Thread() {
@Override
public void run() {
int what = 0;
try {
mTwitter.updateStatus(review);
} catch (Exception e) {
what = 1;
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String text = (msg.what == 0) ? "Posted to Twitter" : "Post to Twitter failed";
Toast.makeText(TestPost.this, text, Toast.LENGTH_SHORT).show();
}
};
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
@Override
public void onComplete(String value) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
mTwitterBtn.setText(" Twitter (" + username + ")");
mTwitterBtn.setChecked(true);
postToTwitter = true;
Toast.makeText(TestPost.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
}
@Override
public void onError(String value) {
mTwitterBtn.setChecked(false);
Toast.makeText(TestPost.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
}
Update 2011-10-01
- Fix authorization failed bug when attempt to authorize after logging out. This was caused by an exception (java.lang.IllegalStateException: consumer key/secret pair already set) was thrown by setOauthConsumer(consumerKey,secretKey) method of Twitter class. This method should be called once.
You can download the source code here (with external jars) or via github here
Related post:
Hi Good Evening..i have downloaded twitter app from here:https://github.com/lorensiuswlt/AndroidTwitter
here i have to run the app which means the twitter login page is opened.
i have enter correct login detail means its go to post page..here i have wrote Hi Good morning.afterthat click submit button means thr review posted message is displayed on app.Now i have to check my twitter home page means the data is not posted.
why the message is didn’t post on home
please give me solution for these
hey
i have tried your code..but i am getting only one error in twitterApp.java file in this line
“mtwitter.setOAuthAccessToken(mAccess)”
could you plz help me out….i added all jar file
Thanks for the example app. I did have to update the URLs to get things working. Thanks again.
mHttpOauthprovider = new DefaultOAuthProvider(”https://api.twitter.com/oauth/request_token”,
“https://api.twitter.com/oauth/access_token”,
“https://api.twitter.com/oauth/authorize”);