Tuesday, February 8, 2011

Integrating Twitter in Android

I know I've been neglecting my blog the past weeks, but I had some sort of NDA at my company so I wasn't allowed to share code.
Now that my project has finished I can start filling this page up and maybe help some of you guys out :)

Im gonna start with Twitter integration.
Unlike Facebook, Twitter doesn't have an easy quick-integratable API. There are, however, 3rd party libraries like Twitter4j. I got pointed to this library by a good friend and after some hours I got it to work. Let's start, shall we?

1) First, download the library at http://twitter4j.org/en/index.html
You must also download these 2 files
  • signpost-commonshttp4-1.2.1.1.jar
  • signpost-core-1.2.1.1.jar
Just enter the filenames in Google and you can download them.

From the downloaded file from twitter4j you need to extract twitter4j-core-2.1.9-SNAPSHOT.jar

2) Add these 3 libraries to your project.
3) As you already should know by now, Twitter uses Oauth for authentication. Simple letting users enter login credentials isn't allowed anymore since August 2010 (unless you ask permission from Twitter, then you can use xAuth).

First we need to authenticate. I created this simple method for authentication:


public void authTwitter() {
try {
httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
httpOauthprovider = new CommonsHttpOAuthProvider(
"http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize");
httpOauthprovider.setOAuth10a(true);

String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, CALLBACKURL.toString());
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
}
}



Note that consumerKey and consumerSecret are both Strings which are defined in the field of the class.
CALLBACKURL has to be something like "packagename://classname" In my project it's sosInternational://Twit"

What this does is open the browser with the authentication URL and logging in to Twitter. After the user authenticates and grants permission the browser redirects back to your app (Twit.java in my example) and from there you can receive the so called AccessToken. With that AccessToken you have permission to control the user account.



@Override
public 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 {
httpOauthprovider.retrieveAccessToken(httpOauthConsumer, verifier);
// Saving the AccessToken for further use
SharedPreferences settings = getSharedPreferences("Twitter", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Token", httpOauthConsumer.getToken());
editor.putString("TokenSecret", httpOauthConsumer.getTokenSecret());
editor.commit();

sendtoTwitter();
} catch (Exception e) {
}
}
}


Here I save the retrieved AccessToken to SharedPreferences so the user doesn't have to authenticate each time it want's to post something.

4) Now we have full control over the users Twitter account we can tweet things. Here is my method for tweeting

sendtoTwitter():


public void sendtoTwitter() {
if (settings.getString("Token", null) != null && settings.getString("TokenSecret", null) != null) {
prog = ProgressDialog.show(this, "", "Tweeten...", true);
Post post = new Post();
post.start();

} else {
authTwitter();
}
}

At first it tries to find the AccessToken I might have saved. If it isn't able to find it, it authenticates.

I made a new class for the tweeting so I could make a ProgressDialog:


private class Post extends Thread {
@SuppressWarnings("deprecation")
@Override
public void run() {
Looper.prepare();
a = new AccessToken(settings.getString("Token", null), settings.getString("TokenSecret", null));
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
twitter.setOAuthAccessToken(a);

// Send Tweet
try {
twitter.updateStatus(tweetTextView.getText().toString());

} catch (TwitterException e) {
}
handler.sendEmptyMessage(0);
}

private Handler handler = new Handler() {

@Override
public void handleMessage(Message msg) {
prog.dismiss();
Toast.makeText(getBaseContext(), "Bericht getweet!", Toast.LENGTH_SHORT).show();
finish();
}
};
}


After this you should be able to use Twitter in your app!

Monday, November 29, 2010

Welcome

Hi all!

Welcome to my first blog.

I came up with the idea for this blog last week. I just got started with developping for android and found out what a pain in the ass it is.

I searched days for answers on forums, question banks, blogs etc. and I'm extremely thankful for all the people who have helped me so far (especially Zarah).

So keeping in thought that other beginners like me could have some problems in coding, I started this blog to help and spread the wisdom =)

I'll post my experience through the beginning of Android development in the hope others will benefit.

Even if I helped 1 person, i'll be happy =)

Hope you enjoy my blog!

Gr,

Galip