Monday, June 27, 2011

For all my Code thirsty Friends (Twitter Code For Android Applications)

Download Full Source from Here


Hope this will be resolving Most of the queries ....

OPENNESS IS OUR RIGHT :)

Please let me know if anything is required.

package abhinavasblog.blogspot.com;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.twitter.android.TwitterApp;
import com.twitter.android.TwitterApp.TwDialogListener;

/*
 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.
 */

public class TwitterForUActivity extends Activity {

private TwitterApp mTwitter;

/** Called when the activity is first created. */
private static final String CONSUMER_KEY = "GPjUBdt9yn3FYTO9RcW2w";// "GPjUBdt9yn3FYTO9RcW2w";
private static final String CONSUMER_SECRET = "M0uxQG8r4f5ogfMDH0phU0FQvaYBOo2Bv6hP98xiag"; //"M0uxQG8r4f5ogfMDH0phU0FQvaYBOo2Bv6hP98xiag";

private enum FROM {
TWITTER_POST, TWITTER_LOGIN
};

private enum MESSAGE {
SUCCESS, DUPLICATE, FAILED, CANCELLED
};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTwitter = new TwitterApp(this, CONSUMER_KEY, CONSUMER_SECRET);
}

/**
* Handling click events of button used to launch
*
* @param v
*/
public void onClick(View v) {
mTwitter.setListener(mTwLoginDialogListener);
mTwitter.resetAccessToken();
if (mTwitter.hasAccessToken() == true) {
try {
mTwitter.updateStatus(TwitterApp.MESSAGE);
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
} else {
mTwitter.authorize();
}
}

/**
* Show toast messages
*
* @param twitterPost
* @param success
*/
private void postAsToast(FROM twitterPost, MESSAGE success) {
switch (twitterPost) {
case TWITTER_LOGIN:
switch (success) {
case SUCCESS:
Toast.makeText(this, "Login Successful", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
default:
break;
}
break;
case TWITTER_POST:
switch (success) {
case SUCCESS:
Toast.makeText(this, "Posted Successfully", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(this, "Posting Failed", Toast.LENGTH_LONG)
.show();
break;
case DUPLICATE:
Toast.makeText(this,
"Posting Failed because of duplicate message...",
Toast.LENGTH_LONG).show();
default:
break;
}
break;
}
}

/**
* Twitter Dialog Listner.
*/
private TwDialogListener mTwLoginDialogListener = new TwDialogListener() {

@Override
public void onError(String value) {
postAsToast(FROM.TWITTER_LOGIN, MESSAGE.FAILED);
Log.e("TWITTER", value);
mTwitter.resetAccessToken();
}

@Override
public void onComplete(String value) {
try {
mTwitter.updateStatus(TwitterApp.MESSAGE);
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
}
};
}


56 comments:

Anonymous said...

Hi, I have successfully integrated your code into my project. However, when I change the minSDK to android:minSdkVersion="11" (HoneyComb) I get the errors below. I'm not sure of the cause, but it may be because of a twitter thread running on the main UI thread. Could you help me narrow down the source of the error?

And again both of these errors will not occur unless the minSDK is set to 11.

java.lang.NullPointerException
at com.example.android.hcgallery.MainActivity$1.onComplete(MainActivity.java:881)
at com.twitter.android.TwitterApp$1.handleMessage(TwitterApp.java:233)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:132)
at android.app.ActivityThread.main(ActivityThread.java:4025)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:491)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)

java.lang.IllegalStateException: consumer key/secret pair already set.
at twitter4j.TwitterOAuthSupportBaseImpl.setOAuthConsumer(TwitterOAuthSupportBaseImpl.java:234)
at twitter4j.Twitter.setOAuthConsumer(Twitter.java:54)
at com.twitter.android.TwitterApp.configureToken(TwitterApp.java:90)
at com.twitter.android.TwitterApp.access$7(TwitterApp.java:88)
at com.twitter.android.TwitterApp$3.run(TwitterApp.java:161)
Error getting access token

Unknown said...

well a null pointer is there in your code.. it will be better if you code... i will be able to help if you can share the live of code at com.example.android.hcgallery.MainActivity$1.onComplete(MainActivity.java:881)

Sam said...

Hi Abhinava its working fine till login..But how do we tweet and clear its crendentials????

Unknown said...

@Sam : mTwitter.updateStatus("");
use this method to post any data on your twitter wall... (to tweet)
to clear data .. just use

mTwitter.resetAccessToken().

rakesh said...

HI,
I have used sample code which is given by u, but I am not able to loggin in to the twitter when I pressed the button "Post some data".

Without giving user credentials how it will authenticate.....??

can u plz give me clear Idea about this.

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

rakesh said...

Hi Abhinav,

I used the same code, But I am not able to authenticate.

Unknown said...

hi Rakesh,
The app cannot authenticate you without providing credentials :)
please make sure that if you have stored the username and password on first signup.

rakesh said...

Thank U Abhinav,

Actually my question is, When I palce ur sample keys the code is working properly.
That means in code u have placed only consumer_key & consumer_secret. In same way I replaced my own app consumer_key $ consumer_secret. Till not able connect to the twitter.

Even I place the Tweet_Auth_key & Tweet_Auth_secret_key, Tweet_user_name in Twittersession.java of ur code.

rakesh said...

Hi Abhinav,

What I have replace in CALLBACK_URL = "twitterapp://connect";

1--> when replace with our companies URL, it is not able to tweet.

2--> When I replace with empty URL, Its not able to connect to twitter.

Can u plz help me...!!

Unknown said...

Hi Rakesh,
the call back url helps only for identifying ur application
Url must be in form of twitterapp://abhinavasblog or anything like this.. its helpful only if you declare it in your application
you cannot have it empty as Oauth needs some url to redirect you to.

you may need to wait for 1 ~ 2 hours after obtaining your consumer key and consumer secret as it takes some time to be activated from twitter side.

Hope it helps now :)

rakesh said...

Thank u Abhinav,

The code wich u have given Twitter native is working perfectly. But when I intigrited in my app, when i click on the post button I am not able to see the Twitter's login page. I am getting our applications background image on twitters login page.

Can u plz help me where I am getting the layout over loaded......??

Plz help me........!!

yogibaba said...

Hi Abhinav,
I have downloaded and compiled your code on Android 2.2 SDK.But when I launch the application on emulator and click on 'Post Some data' button , it is not doing anything. Only for sometime 'Initialising..' dialog box appear.
Please let me know what could be the cause of the problem.
Thanks

Yogesh said...

Hi Abhinav,
IS the same Android twitter code work for 2.2 SDK? As in my case it is not working.
Thanks,

Unknown said...

hi abinav,
i have used your code. it works good when i placed your consumer and secret key. but it never works for an my own app consumer key and secret key.. whats the problem with that key. same keys working in iphone perfectly .. can u help me?

Anonymous said...

Hi..This article is very helpful. how can i use this to post image to twitpic?

Unknown said...

@Rakesh: looks like the application is using some simmilar resource names. Please check on that.. its quite hard to state about error without any code/logs.
@yogibaba: can you please put up some logs, that will be helpful..
@Yogesh: yes the code works across right from 2.1 (it should technically work for 1.6 also but havent checked it with that)

sujit said...

Thanks its work for me ....

Anonymous said...

from where i can find jar file that u have added ??

Unknown said...

Hi I have already attached placed all the jar in the source.. you just need to link them

Anonymous said...

first of all thanks for sharing, but when I am integrating it with my app its not working.. also I still have confusion about the callback URL.. at the time of creating the app what shd be given there??
If not there then what shd be given in the code(basically how does it affects and what is the process to declare call backURL)

Bhai its been 10 days I am stuck with this Twitter.. all the projects I import work great but when I integrate them then its all the errors.. :(
I hope you will help
Thanks & Regards
Gurvinder

Unknown said...

Hi Gurvinder,
the callbacks are required in two ways one is that they are declared in twitter as callbacks when you register your app it asks for callback url.
I have updated and attached the screenshot of my dev page of twitter .. you can compare with yours in case you still have any doubts.

Anonymous said...

Thanks for Reply, actually when i give the callback URL, my app first asks for the twitter credentials, and at the time of redirecting .. it simply opens the callback URL in the browser.. whereas when I tried your code, it does has call back URL but it do not open the callback URL in the browser simply redirect to the activity.. not sure what wrong I am doing.. :(

Anonymous said...

Ronak :
Thanks a lot boss...works great...
ADDITION::
When i login to app with my app key and all, and click on post button your app posts my tweet once,for continuous posting (DIFFERENT MESSAGES) I need to Rebuilt the app and then run it...
NOW THE SOLUTION IS, Open TwitterApp.java ---> in public void processToken(String callbackUrl)---> CHANGE THE VALUE int what = 50; --> Run it...

I have suffered but I dont want you to suffer....Thanks a lot..
ronak167@gmail.com

Unknown said...

@Ronald: thanks... :) I hope it will be helpful to all who need it...

ahsan said...

getting the following error (i am using twitter4j core 2.2.4):



09-25 20:44:58.934: WARN/System.err(3741): oauth.signpost.exception.OAuthExpectationFailedException: Request token or token secret not set in server reply. The service provider you use is probably buggy.
09-25 20:44:58.934: WARN/System.err(3741): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:202)
09-25 20:44:58.934: WARN/System.err(3741): at oauth.signpost.AbstractOAuthProvider.retrieveAccessToken(AbstractOAuthProvider.java:97)
09-25 20:44:58.934: WARN/System.err(3741): at corp.encameo.app.TwitterApp$3.run(TwitterApp.java:145)
09-25 20:44:58.981: ERROR/TWITTER(3741): Error getting access token


any help ?

Julio said...

Hi Abhinava, thank you for your code. It has been the most useful I found online.

Please excuse my ignorance but how I handle the part when I get the PIN? What do I do next?

On the iPhone, this gets automatically done by the libraries but here I am lost.

Thank you,

Julio

inder said...

Hi Abhinav. Awesome code and thanks for sharing. This worked well for me. Do you have this hosted on a project somewhere? I was thinking of adding it to https://code.google.com/p/twitter-android/

You are welcome to join the project and help improve, if you want.

Unknown said...

Hey Julio,

for now we have not handled that part in the library. Will be doing the same in future.

Unknown said...

Hi inder
Thanks for the comments and sugestion.
Yes i alrady have created the space but not able to find time to push the source .. Will be updating you very soon on this.

thanks again. :)

inder said...

I have merged this code in:
https://code.google.com/p/twitter-android/ along with some refactorings (to hopefully improve it a little bit). The goal is to structure this as a reusable Android library which I intend to use in my own Android games.

Would love to have you join as a co-owner.

inder said...

Hi Abhinav: Send me your gmail id to join https://code.google.com/p/twitter-android

Unknown said...

hi Inder sorry for the delay.
Had been busy in some stuff.

anyways, my id is abhinava.sr[at]gmail.com

Parthraj said...

Hi Abhinav,
thanks for the tutorial, Its awesome.
I just wanna ask is there any way to login into twitter account without showing the twitter webpage to the user?

I mean, i wanna create my custom login UI with textbox of username and password.

Thanks in advance.

Parthraj said...

Hi Abhinav,
thanks for the tutorial, Its awesome.
I just wanna ask is there any way to login into twitter account without showing the twitter webpage to the user?

I mean, i wanna create my custom login UI with textbox of username and password.

Thanks in advance.

Anonymous said...

Hi Abhinav,

Great coding stuff... Have bookmarked ur blog!!!

Have tried using your code and have even looked at the commnent of Ronak in the Blog itself and I did that change also... Now if a new user wants to access the application he / she has to logout from the Twitter Page and then try again, My Question is how can I clear all the credentials passed.

Please help me..

inder said...

Abhinav: I captured the latest feature request by "Anonymous" in
https://code.google.com/p/twitter-android/issues/detail?id=2

Unknown said...

mTwitter.resetAccessToken();

Anonymous said...

Hi Abhinav,

I have a problem regarding Login,as you have mentioned I have created twitter consumer key and secret key, but when I put that in the code its not working. I replaced my site name with as you have mentioned in the previous comment as "twitterapp" also,even then I am getting login failed message.

Thanks....

Anonymous said...

HI Abhinav,

Just had a question as how to logout the user to ensure that other user can login as resetAccessToken has no effect and a second authorization results in a KEY/SECRET already set. Can u provide any workaround for the same.

Naveen said...

Hi Abhinav,
I have successfully integrated yours twitter code in to my application. but i have small problem i.e i have to post dynamic message instead of static message.Is it possible to posts dynamic messages Please help me.
Thanks
Naveen

Unknown said...

I dn't knw wh ur code is not posting the tweet. it was working 2 days earlier. plz telll me what had happened?

arun said...

Hi abhinav,

04-09 09:52:12.187: E/AndroidRuntime(735): FATAL EXCEPTION: main
04-09 09:52:12.187: E/AndroidRuntime(735): java.lang.VerifyError: com.twitter.android.TwitterApp
04-09 09:52:12.187: E/AndroidRuntime(735): at abhinavasblog.blogspot.com.TwitterForUActivity.onCreate(TwitterForUActivity.java:48)


This exception occurs at the start of application. I am not able to rectify this. Please tell me what is the issue.

Anonymous said...

Hi Abhinav,

Thanks for sharing this code.. this is a real help.
But when I tried to download the .zip file, I didn't found that file there.

Can you please share the full project with me for my reference.

Thanks in advance!

-Ruchi

SMART said...

Hi Abhinav,

Please i want that full source code.
As it gets deleted from that 4shared.com website.
so please can u again upload it.

SMART said...

Hi Abhinav.

Please can i get full source code.
As it gets deleted from 4shared website.
So please can u again upload it.

Bharathi said...

Not able to download code. It has been deleted. Can u post it again

onlineworldtour said...

hi abhinav i need full code for implementing the post a status to twitter...its not working..plz send the zip file to my gmail id...
bhanotsachin@gmail.com

thanks in advance

Unknown said...

Sorry everyone for super delay... was also searching my source... :D

Found it and have updated the link...

cheers.. :)

Anonymous said...

When I try to run the code as it is, it shows "Unfortunately, TwitterForU has stopped working" before even showing the login page. Can you help me with this?

sagar said...

i had two kinds of errors trying this code:
1) The application used to crash
Solution: Just rename the library folder "lib" to "libs"...It will work
2) After pressing the button "Post Data" , it said "Login Failed"... here the call back URL should not be empty...i just used "https://twitter.com/" and i was able to post tweet to my account successfully....glad if i could help...

Anonymous said...

Thanks Abhinav. This helped me...

Anonymous said...

same error m lso gettin...@arun

mindfreak said...

Hey abhinav when i am login to twitter I got "Whoa there! The request token for this page is invalid. It may have already been used, or expired because it is too old. Please go back to the site or application that sent you here and try again; it was probably just a mistake." this error message on twitter page.this error shows that my access token is expired but what should i do to fix this problem Actually I am newbie for twitter can you please help me?? here is my code




package com.mysnl.gui.twitter;

import java.net.URL;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.Uri;
import android.os.StrictMode;
import android.util.Log;

import com.mysnl.gui.twitter.TwitterDialog.TwDialogListener;
import com.mysnl.utils.AppConstant;
import com.mysnl.utils.SocialNetworkSetting;

public class LoginTwitter {

// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
private Context mContext;
private String url;
private TwDialogListener mListener;

@TargetApi(9)
@SuppressLint("NewApi")
public LoginTwitter(Context mContext) {
this.mContext=mContext;
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(AppConstant.TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(AppConstant.TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken =getRequestToken();
url=requestToken.getAuthenticationURL();
mListener = new TwDialogListener() {
@Override
public void onComplete(String value) {
System.out.println("CallBack URL ::::: "+value);
Uri uri=Uri.parse(value);
// oAuth verifier
String verifier = uri.getQueryParameter(AppConstant.URL_TWITTER_OAUTH_VERIFIER);
AccessToken accessToken;
try {
accessToken = getTwitterInst().getOAuthAccessToken(requestToken, verifier);
long userID = accessToken.getUserId();
User user =getTwitterInst().showUser(userID);
String username = user.getName();
String url=user.getProfileImageURL();
SocialNetworkSetting.INSTANCE.setmTwAccessToken(accessToken.getToken());
SocialNetworkSetting.INSTANCE.setTwTokenSecret(accessToken.getTokenSecret());
SocialNetworkSetting.INSTANCE.setTwProfilePic(url);
SocialNetworkSetting.INSTANCE.setTwUserLoggedIn(true);
SocialNetworkSetting.INSTANCE.setTwUserName(username);
} catch (TwitterException e1) {
e1.printStackTrace();
}catch(Exception ex){
ex.printStackTrace();
}
}

@Override
public void onError(String value) {
mListener.onError("Failed opening authorization page");
}
};
} catch (TwitterException e) {
e.printStackTrace();
}catch(Exception ex){
ex.printStackTrace();
}
}


public RequestToken getRequestToken() throws TwitterException{
requestToken = twitter.getOAuthRequestToken(AppConstant.TWITTER_CALLBACK_URL);
return requestToken;
}

public Twitter getTwitterInst(){
return twitter;
}

public Boolean isTwitterLoogedIn(){
return SocialNetworkSetting.INSTANCE.isTwUserLoggedIn();
}

public TwDialogListener getListener(){
return mListener;
}

public String getUrl(){
return url;
}
}

Mike Storms said...

Brilliant, man.
Concise and well explained.
Thank you very, very much.

Unknown said...

Dear abhinava, would you like to give a complete example including on how to update status with it.

see here's my code but it doesn't work :

check_twitter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
final TwitterAuthDialog dialog = new TwitterAuthDialog(TambahProdukActivity.this, TwitterConstantValue.TWITTER_CONSUMER_KEY, TwitterConstantValue.TWITTER_CONSUMER_SECRET, new TwitterDialogListener() {

@Override
public void onTwitterkError(TwitterException e) {
// TODO Auto-generated method stub
check_twitter.setChecked(false);
}

@Override
public void onError(TwitterDialogError e) {
// TODO Auto-generated method stub
check_twitter.setChecked(false);
}

@Override
public void onComplete(Uri values) {
// TODO Auto-generated method stub
/* what should i do here*/
}

@Override
public void onCancel() {
// TODO Auto-generated method stub
check_twitter.setChecked(false);
}
});

dialog.show();
}else{

}
}
});

Unknown said...

Thank you for your code. Some are useful.
Looking forward a java code about qr code control.
Best regards.