Wednesday, September 15, 2010

Using Twitter with OAuth On Andorid

Hi There..
many of my friends have been looking to find a way via which they can create applications which have twitter functionality..
well m posting here a small snippet.. this snippet will be helpful for you to understand how can we make twitter work in our application..

Libs we will be using: Twitter4J


package abhi.twitter;

/*
Copyright [2010] [Abhinava Srivastava]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import twitter4j.Twitter;
import twitter4j.http.AccessToken;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class OAuthHelp {

private static final String APPLICATION_PREFERENCES = "tweet_preferences";
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SEKRET_KEY = "auth_secret_key";
private SharedPreferences preferences;
private AccessToken accessToken;
private String consumerSecretKey;
private String consumerKey;

/**
* OAuthHelp class constructor loads the consumer keys
*
* @param context
*/
public OAuthHelp(Context context) {
preferences = context.getSharedPreferences(APPLICATION_PREFERENCES,
Context.MODE_PRIVATE);
loadConsumerKeys();
accessToken = loadAccessToken();
}

/**
* Depricated method has been used
*
* @param twitter
*/
@SuppressWarnings("deprecation")
public void configureOAuth(Twitter twitter) {
twitter.setOAuthConsumer(consumerKey, consumerSecretKey);
twitter.setOAuthAccessToken(accessToken);
}

/**
* true is accesstoken available false other wise
*
* @return boolean
*
*/
public boolean hasAccessToken() {
return null != accessToken;
}

/**
* Stores access token in preferences
*
* @param accessToken
*/
public void storeAccessToken(AccessToken accessToken) {
Editor editor = preferences.edit();
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SEKRET_KEY, accessToken.getTokenSecret());
editor.commit();
this.accessToken = accessToken;
}

/**
* Loads acess token from SharedPreferences
* @return
*/
private AccessToken loadAccessToken() {
String token = preferences.getString(TWEET_AUTH_KEY, null);
String tokenSecret = preferences.getString(TWEET_AUTH_SEKRET_KEY, null);
if (null != token && null != tokenSecret) {
return new AccessToken(token, tokenSecret);
} else {
return null;
}
}

/**
* Loads default consumer keys
*/
private void loadConsumerKeys() {
consumerKey = "tkU0PAt5vtvY169JO47Duw";
consumerSecretKey = "nYEBvt86WpyXwD84HoePW6q0gFzi4rXhhrEsZghCzlI";
}
}

then just make a simple linking via Calling Activity..


package abhi.twitter;

/*
Copyright [2010] [Abhinava Srivastava]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
* @author abhinava_srivastava
*/

public class TwitterApp extends Activity {

/**
* Twitter instance object
*/
private Twitter twitterConnection = null;
private OAuthHelp oHelper = null;
private RequestToken requestToken = null;
private AccessToken accessToken = null;
private WebView webView = null;
private Context context;
private Handler handleEvent = null;

private static final String CONSUMER_KEY = "tkU0PAt5vtvY169JO47Duw";
private static final String CONSUMER_SECRET = "nYEBvt86WpyXwD84HoePW6q0gFzi4rXhhrEsZghCzlI";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handleEvent = new Handler();
twitterConnection = new TwitterFactory().getInstance();
context = this;
oHelper = new OAuthHelp(this);
}

/**
* Connects to twittter
* @param v
*/
public void getTwitter(View v) {
handleEvent.post(new Runnable() {
@Override
public void run() {
if (oHelper.hasAccessToken()) {
oHelper.configureOAuth(twitterConnection);
try {
twitterConnection.updateStatus("Hii!!!!");
} catch (TwitterException e) {
Log.d("TWEET", "Error Updating status " + e.getMessage());
e.printStackTrace();
}
} else {
try {
twitterConnection.setOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
requestToken = twitterConnection
.getOAuthRequestToken("");
webViewDialog(requestToken.getAuthorizationURL(), 0);
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
});
}

/**
* Shows Dialog for authentications
*
* @param authorizationURL
* @param type
*/
private void webViewDialog(final String authorizationURL, final int type) {
LinearLayout container = new LinearLayout(this);
container.setMinimumWidth(200);
container.setMinimumHeight(320);
webView = new WebView(this);
webView.setMinimumWidth(200);
webView.setMinimumHeight(380);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(authorizationURL);
container.addView(webView);
Builder webDialog = new AlertDialog.Builder(this);
webDialog.setView(container).setTitle("Web Settings")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
if (type == 0) {
twitterPinCodeDialog();
dialog.dismiss();
}
// dialog.dismiss();
}
}).show();
}

/**
* Pin code dialog Requests the user to enter pin shown on twitter
*/
public void twitterPinCodeDialog() {
LinearLayout pinHolder = new LinearLayout(this);
pinHolder.setGravity(Gravity.CENTER);
final EditText editPinCode = new EditText(this);
editPinCode.setGravity(Gravity.CENTER);
editPinCode.setHint("Pin Code");
editPinCode.setWidth(200);
pinHolder.addView(editPinCode);

Builder pinBuilder = new AlertDialog.Builder(this);
pinBuilder.setView(pinHolder).setTitle("Twitter Pin Code Entry")
.setMessage(
"Please enter displayed twitter code into the field")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
if (editPinCode.getText().toString() != null
&& !editPinCode.getText().toString().equals("")) {
try {
accessToken = twitterConnection
.getOAuthAccessToken(requestToken,
editPinCode.getText()
.toString());
oHelper.storeAccessToken(accessToken);
Log.i("Access Token:", accessToken.getToken());
Log.i("Access Secret:", accessToken
.getTokenSecret());
twitterConnection
.updateStatus("Tweeted Successfully - Abhinava Srivastava");
} catch (TwitterException te) {
if (401 == te.getStatusCode()) {
System.out
.println("Unable to get the access token.");
} else {
te.printStackTrace();
}
}
} else {
Toast.makeText(context, "Pin code is required",
Toast.LENGTH_SHORT).show();
dialog.dismiss();
twitterPinCodeDialog();
}

}
}).setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
Toast
.makeText(
context,
"To share your news please complete login next time",
Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}).show();
}
}

Do not forget to add permission of INTERNET..
@nJoy!

44 comments:

Shubham said...

Hi Abhinav ,Thnx fro this sample code.

Shubham said...

Hi abhinav I try your sample bt nothing happening at my Twitter Home screen .

n pls explain what these keys contain:
TWEET_AUTH_KEY = "auth_key";

TWEET_AUTH_SEKRET_KEY = "auth_secret_key";

Shubham said...

I am getting private AccessToken

loadAccessToken() {...

String token =null ?
pls resolve this one.

Shubham said...

Hi agaiin pls reply... when getTwitter(view)..call.

pls reply asap.

My Blog said...

Hi, thanx for the code, it works perfectly....

Shubham said...

Hi Abhinav's , Sorry but stl i not got any responce from your side. Can you please specify. How user authenticate and how exactly it work .
Please suggest me.

Shubham said...

hi abhinav again, Where we give user credential here.

Shubham said...

I am getting null every time from loadAccessToken(), bcz i m not getting exactly mean by TWEET_AUTH_KEY and TWEET_AUTH_SEKRET_KEY .

Even I register an application from http://dev.twitter.com/apps and generate Access Token (oauth_token) and Access Token Secret(oauth_token_secret). plesae suggest me solution of all these problems.

the legend said...

hi,subham u have to register ur application with twitter to get the key and the secret

hEENa!!! said...
This comment has been removed by the author.
hEENa!!! said...

HI Abhinav,
Thanks for code... it works fine accept on webviews the virtual keyboard does not pops up ....(for login and entering pin) .. can you help me out ?

@shubham :
TWEET_AUTH_KEY : access token(check ur twitter account where you have registerd the app, go to the application details or view my access token)
TWEET_AUTH_SEKRET_KEY =access secret

parmar said...

thanx.abhi...this code is working nice....but i have one problem in this...when browser window open in emilator than i can write username and passoword through keyboard..but it can not open virtual keyboard in simulator ...i think with this problem it we can not write anything in editbox and we cant run this application...if u hava an idea ,help me......

Carl said...

thx for the post. i'm new to android, so this is VERY helpful. I do hv a couple of questions:
1. in OAuthHelp, where can i get the tweet prefernces/APPLICATION_PREFERENCES? 2. as is, the application runs with no errors, but nothing happens??

any help will be greatly appreciated.

koteswar said...

hi abhinav i am new to android i need to interface my sample application with twitter i went through you sample code but i am getting errors so please send me the full code of the project in zip file
i will be greatfull to you in advance
my mail id is :koteswarme2010@gmail.com

Naveen shrivastva said...

how to set this here
TWEET_AUTH_KEY = "auth_key";

TWEET_AUTH_SEKRET_KEY = "auth_secret_key";

Olga Gavrilenko said...

Great sample. Thanks

sanjay said...

Thanks Abhinava, I could able to run the program without any issue,

smita said...

how to make a simple linking via Calling Activity?

smita said...

How to make a simple linking via Calling Activity?

Saurabh said...

what is twitter4j in this code...
i have no found this type of package in ur code...

Sumant said...

Hi thnx for code put download link where all project can be downloaded..

Arpit said...

Hi Abhinav, im using twitter4j-core-2.1.0.jar

and getting exception in line: accessToken = twitterConnection.getOAuthAccessToken(requestToken, editPinCode.getText().toString());


please help, if possible share the code too for downloading whole application.

thanks
cheer :)

Sameer said...

Hi,
I tried your code from your site and I am getting 2 errors in the Twitter App class.
1. accessToken = twitterConnection.getOAuthAccessToken(requestToken,editPinCode.getText()
.toString());
2.requestToken = twitterConnection.getOAuthRequestToken("");
I import twitter4j.http.requestToken but still gives me an error.
Can someone please help me.
I appreciate it.

Dixit Wadhwani said...

can u plz send me your whole code @ my email addr. dixitwadhwani@gmail.com

Rajani said...

Hi
I have tried your sample.But when I tried to get the Access Token it gives force close.I am getting null every time from loadAccessToken()

How to resolve this one?.

MAD'u CrY said...

Hi frds, I am Unable to run the code.It directly gives me force close while running.In loadAccessToken() method it throws NullPointerException. How to resolve this. Any idea?

Rahul Ranjan said...

Hi,

Thanks for ur code, it really help me lot's..

I have one request to u, if u know how to integrate linkedin with android application same as twitter, then plz share with us..

Thanks & Regards,
Rahul Ranjan

harshada said...

Hi Abhinav,
it's work fine, how can we call status/filter API & how can we find its id's for direct message.
awiting for youe reply,
Thanx in advance.

Harsha.

chitgoks said...

your sample is lacking. it doesnt have anything that tells how to use it, your main.xml is also not present

Vinayak Kulkarni said...

Hi sir, I am your student from sunbeam wimc feb 2011 batch. I implemented the code posted by you. I want to get logged user information from twitter in my android app. How get this done. plz help. Even you can reply me to vsk_134@yahoo.co.in

Thanks.
Vinayak

Vinayak Kulkarni said...

Sir plz let me know how to get user info from twitter in android app ASAP.

yati said...

Hi,i am not getting anything when i try to run the code.Can you please mail me the application me email id is:yatibawri
@gmail.com

Abhinava's Blog said...

hey friends sorry for not being able to send you replies.. EXTREMELY SORRY!!

Shubham: TWEET_AUTH_KEY and TWEET_AUTH_SECRET_KEY these are the application keys that you need to obtain from the Twitter as u need to register you application with them...

Heena: This has been found an issue of WebView and have been reported to Android Community .. there is some issue with Virtual Keyboard on WebView. Well there is a work around available... You need to Add an action listner and say view.requestFocus(). This should resoulve your keyboard issue.

smita: Sorry didnt get your question can you please elaborate?

Abhinava's Blog said...

New implementation with Code check out the http://abhinavasblog.blogspot.com/2011/06/for-all-my-code-thirsty-friends-twitter.html

have attached source of running application.

rakesh said...

Hi Abhinav, thank u for explaining the code. But I am not able to authenticate.


ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(251): Error during OAUth retrieve request token


ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(251): oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.


Plz expalin me why i am getting this error.


Thanks in advance.......!!!

Unknown said...

Where exactly can i provide with Credential like username and password in the app because for me am getting mesage as not logged in..?

Anonymous said...

Hi, i tried your code, provide keys, bt it still didnt show anything on screen

basanta said...

if u give that twitter integration in form of a project ,it will be better for implementing.

Murali said...

Hi Abhinava,
Am used ur code and change my consumer key and secret key. And an getting (getting error access token).
pls help me..... am really struck ...
thank advance.....

Murali said...

Hi Abhinava,
Am used ur code and change my consumer key and secret key. And an getting (getting error access token).
pls help me..... am really struck ...
thank advance.....

Abhinava Srivastava said...

Anonymous : a log will be better to understand the issue.
Basanta: have shared the code for new implementation.
Murali: I hope you are using the correct keys, also many a times user try to use the key as soon as they generate them. That will not work as it seems like it takes around 24 to 48 hrs to activate the key. So patience my friend... :)

Anonymous said...

Hi Abhinav,

I cant get the web view to load.
Could you also please share your main.xml?

Thanks

abey350 said...

It works fine but with one important change:

call getTwitter(); from onCreate().

Also, parameter View v is not required in getTwitter() method.

Anonymous said...

hey abhinav.. m new to android ... can you email me the tweeter libraries / api's that need to be added to my project folder for my app integration with tweeter..
@jain.nitk09@rediffmail.com