Hi Mukesh,

thanks for sharing the code!

One question I got regarding the callback url:

in your sample you're using the callback url myapp://mainactivity, but
how can you actually register such callback url that doesn't start
with http on twitter? When I try to register such url in my app
details on twitter, I would get an error "Invalid url format". Or
sometimes a message "please contact api[at]twitter.com to add the
protocol, etc. etc.". So is that the way you did as well - having the
twitter api team enable the custom 'protocol' for you?

Thanks!
Mathias


On Nov 15, 1:55 pm, Mukesh Srivastav <mukicha...@gmail.com> wrote:
> Hi All,
>
> Twitter4jOAuthforAndroidexample by Mukesh,this example would help
> you to understand the usage of Intent after succesfully authentication
> usingOAuthinAndroid.
>
> make use of it and enjoy..
>
> About :OAuth
>
> OAuthis 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 
> implementOAuthfor Twitter.
>
> While implementingOAuthfor Twitter onAndroidplatform, I came
> across hell of out of tutorials and blogs, some might gives different
> ways of usingOAuth. 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 aAndroidApplication, 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;
>
> importoauth.signpost.OAuthProvider;
>
> importoauth.signpost.basic.DefaultOAuthProvider;
>
> importoauth.signpost.commonshttp.CommonsHttpOAuthConsume r;
>
> importandroid.app.Activity;
>
> importandroid.content.Intent;
>
> importandroid.net.Uri;
>
> importandroid.os.Bundle;
>
> importandroid.util.Log;
>
> importandroid.widget.Toast;
>
> import
> twitter4j.Twitter;
>
> import
> twitter4j.TwitterFactory;
>
> import
> twitter4j.http.AccessToken;
>
> importandroid.widget.Button;
>
> importandroid.widget.TextView;
>
> import
> com.sogeti.msl.R;
>
> public
> class OAuthForTwitter extends Activity {
>
> private CommonsHttpOAuthConsumer httpOauthConsumer;
> private OAuthProvider httpOauthprovider;
> publicfinalstatic String consumerKey = "sdOjEI2cOxzTLHMCCMmuQ";
> publicfinalstatic String consumerSecret =
> "biI3oxIBX2QMzUIVaW1wVAXygbynuS80pqSliSDTc";
> privatefinal String CALLBACKURL = "myapp://mainactivity";
> private Twitter twitter;
> private TextView tweetTextView;
> private Button buttonLogin;
>
> // static Twitter jtwit;
>
> /*
> *
> * OnCreate method for class
> */
>
> @Override
>
> publicvoid 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.
> */
>
> privatevoid 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_V
> ERIFIER);
> Toast.makeText(this, verifier, Toast.LENGTH_LONG).show();
> try {
> // this will populate token and token_secret in consumer
> httpOauthprovider.retrieveAccessToken(httpOauthCon sumer, 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 = "#OAuthworking! " + d.toLocaleString();
> // send the tweet
> twitter.updateStatus(tweet);
> // feedback for the user...
> Toast.makeText(this, tweet, Toast.LENGTH_LONG).show();
>
> //twitter.updateStatus("From MyAndroid...");
> /*
>
> 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
>
> protectedvoid 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 = "#OAuthworking! " + 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();
>
> }
> }
> }
>
> privatevoid 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();
>
> }
> }
> }
>
> YourAndroid.mainfest.xml file should looks like this.
>
> <?
> xmlversion="1.0"encoding="utf-8"?>
> <manifestxmlns:android="http://schemas.android.com/apk/res/android";
>
> package="com.sogeti.msl"
>
> android:versionCode="1"
>
> android:versionName="1.0">
>
> <applicationandroid:icon="@drawable/icon"android:label="@string/
> app_name"android:debuggable = "true">
>
> <activityandroid:name=".OAuthForTwitter"
>
> android:label="@string/app_name"android:launchMode="singleInstance">
>
> <intent-filter>
>
> <actionandroid:name="android.intent.action.MAIN"/>
>
> <categoryandroid:name="android.intent.category.LAUNCHER"/>
>
> </intent-filter>
>
> <intent-filter>
>
> <actionandroid:name="android.intent.action.VIEW"/>
>
> <categoryandroid:name="android.intent.category.DEFAULT"/>
>
> <categoryandroid:name="android.intent.category.BROWSABLE"/>
>
> <dataandroid:scheme="myapp"android:host="mainactivity"/>
>
> </intent-filter>
>
> </activity>
>
> </application>
>
> <uses-sdkandroid:minSdkVersion="7"/>
>
> <uses-permissionandroid: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 tohttps://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.

-- 
Twitter developer documentation and resources: http://dev.twitter.com/doc
API updates via Twitter: http://twitter.com/twitterapi
Issues/Enhancements Tracker: http://code.google.com/p/twitter-api/issues/list
Change your membership to this group: 
http://groups.google.com/group/twitter-development-talk

Reply via email to