I am trying to create Twitter login for my Android app. Once I log in, I change the twitter btn title from "Connect with Twitter" to "Disconnect Twitter" and I write out my Twitter username. The only strange thing is that if now I click BACK to quit the application, I go back to where I was before, meaning the button says "Connect with Twitter" againand my Twitter username is not displayed. I am logged in, because if now I click BACK again, I quit the app (go back to the Twitter auth page first) and when I open the app again, the session lives, and the button says "Disconnect Twitter".
Why?
public class Activity_Splash extends Activity {
SharedPreferences sharedPreferences;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private AccessToken accessToken;
User user;
String twitter_username = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mSharedPreferences = getSharedPreferences(TwitterConst.PREFERENCE_NAME, MODE_PRIVATE);
if (!isTwitterLoggedInAlready()) {
Log.i("Splash start", "Twitter is NOT connected");
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TwitterConst.CALLBACK_URL)) {
final String verifier = uri.getQueryParameter(TwitterConst.IEXTRA_OAUTH_VERIFIER);
new Connect_Twitter().execute(verifier);
} else {
Log.i("Splash start", "Twitter is connected");
}
if (isTwitterLoggedInAlready()) {
btn_signupTW.setText("Disconnect Twitter");
btn_signupTW.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
disconnectTwitter();
}
});
} else {
btn_signupTW.setText("Connect with Tw");
btn_signupTW.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
connectTwitter();
}
});
}
private boolean isTwitterLoggedInAlready() {
return mSharedPreferences.getString(TwitterConst.PREF_KEY_TOKEN, null) != null;
}
private void connectTwitter() {
Log.i("Twitter", "connectTwitter()");
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(TwitterConst.CONSUMER_KEY);
configurationBuilder.setOAuthConsumerSecret(TwitterConst.CONSUMER_SECRET);
Configuration configuration = configurationBuilder.build();
twitter = new TwitterFactory(configuration).getInstance();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
requestToken = twitter.getOAuthRequestToken(TwitterConst.CALLBACK_URL);
Log.i("Twitter connectTwitter", "Please authorize this app!");
Activity_Splash.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
Log.i("Twitter connectTwitter", e.getMessage() + "");
}
}
});
thread.start();
}
private void disconnectTwitter() {
Log.i("Twitter", "disconnectTwitter()");
SharedPreferences.Editor e = mSharedPreferences.edit();
e.remove(TwitterConst.PREF_KEY_TOKEN);
e.remove(TwitterConst.PREF_KEY_SECRET);
e.commit();
btn_signupTW.setText("Connect with Tw");
tv_slogan.setText("Log in with Facebook");
}
public class Connect_Twitter extends AsyncTask {
#Override
protected void onPostExecute(String result) {
Log.i("SIKER", result + "");
tv_slogan.setText(result);
btn_signupTW.setText("Disconnect Twitter");
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
try {
accessToken = twitter.getOAuthAccessToken(requestToken, params[0]);
Log.e("Twitter OAuth Token1", "> " + accessToken.getToken());
Editor e = mSharedPreferences.edit();
e.putString(TwitterConst.PREF_KEY_TOKEN, accessToken.getToken());
e.putString(TwitterConst.PREF_KEY_SECRET, accessToken.getTokenSecret());
e.commit();
long userID = accessToken.getUserId();
Log.i("Twitter userID", String.valueOf(userID) + "");
User user = twitter.showUser(userID);
twitter_username = user.getName();
} catch (Exception e) {
e.printStackTrace();
}
return twitter_username;
}
}
}
Twitter just launched Fabric, a set of SDKs with several services to mobile developers. One of them is Twitter kit, it provides Sign in with Twitter, Tweet composing, Embedded tweets and API calls directly from the SDK.
Instead of trying to implement this OAuth flow in your app, Sign in with Twitter with this SDK can be integrated this way:
private void setUpTwitterButton() {
twitterButton = (TwitterLoginButton) findViewById(R.id.twitter_button);
twitterButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
SessionRecorder.recordSessionActive("Login: twitter account active", result.data);
startThemeChooser();
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.toast_twitter_signin_fail),
Toast.LENGTH_SHORT).show();
Crashlytics.logException(exception);
}
});
}
You can find more details about that at:
http://t.co/fabric
https://github.com/twitterdev/cannonball-android (sample android app)
https://dev.twitter.com/twitter-kit/android/twitter-login
To get access to Fabric: fabric.io
This is what I did.
Before calling SettingsActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()))); I save the current activity in Sharedpreferences
When the splash activity comes up (the main that opens every time I open the app) I check this variable in Sharedpreferences and if it's true then I open up SettingsActivity and send the verifier with the intent.
In SettingsActivity now it's easy to log in with this verifier and get user data.
SplashActivity:
if (!isTwitterLoggedInAlready()) {
boolean fromSettingsActivity = mSharedPreferences2.getBoolean(TwitterConst.FROM_SETTINGS, false);
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TwitterConst.CALLBACK_URL)) {
final String verifier = uri.getQueryParameter(TwitterConst.IEXTRA_OAUTH_VERIFIER);
if (fromSettingsActivity) {
Intent intent = new Intent(Activity_Splash.this, SettingsActivity.class);
intent.putExtra("verifier", verifier);
startActivity(intent);
finish();
return;
} else {
new Connect_Twitter().execute(verifier);
}
}
}
SettingsActivity:
Intent iin = getIntent();
Bundle extras = iin.getExtras();
if(extras != null) {
String verifier = extras.getString("verifier");
new Connect_Twitter().execute(verifier);
}
And don't forget to reset the Sharedpreferences value when you click BACK:
#Override
public void onBackPressed() {
mSharedPreferences2 = getSharedPreferences(TwitterConst.FROM_SETTINGS, MODE_PRIVATE);
SharedPreferences.Editor e = mSharedPreferences2.edit();
e.remove(TwitterConst.FROM_SETTINGS);
e.commit();
super.onBackPressed();
}
One more thing
With the current intent the app opens up the SettingsActivity again, so you need to click BACK two times. This is the default behaviour of the Twitter login. To prevent this, use the intent like this:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(requestToken.getAuthenticationURL()));
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
Related
I have two activities, LoginActivity and MainActivity.
LoginActiviy is the launcher Activity, its purpose is to check whether the user is signed in or not if he's signed in; go to MainActivity.
Although I set android:noHistory="true" to LoginActivity the activity's onResume(LoginActivity) is called again when user exits(means onPause called) the program and launch it again.
Did I misunderstood what noHistory means ? if so what can I do to make the OS forget about the existence of LoginActivity?
EDIT : I tried to put this on LoginActivity's onResume , but it calls MainActivity's onCreate, which I don't want
if(!firstTime) {
goToMainActivity();
}
LoginActivity :
public class LoginActivity extends Activity {
protected static final String PASSED_TWITTER = "mosaed.thukair.alsafytooth.LoginActivity";
private static final String TAG = "mosaed.thukair.alsafytooth.LoginActivity";
protected static final int RESULT_BROWSER = 0;
private SharedPreferences prefs;
private Twitter twitter;
private RequestToken requestToken;
private AccessToken accessToken;
private String authUrl;
private Button login;
private boolean firstTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
firstTime = true;
if(isAuthenticated()) {
Log.i(TAG, "splash screen");
setContentView(R.layout.splash_screen);
String token = prefs.getString(Constants.OAUTH_TOKEN, "");
String tokenSecret = prefs.getString(Constants.OAUTH_TOKEN_SECRET, "");
Log.i(TAG, "oauth login");
OAuthLogin(token, tokenSecret);
} else {
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.connect_button);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i(TAG, "clicked");
LoginActivity.this.setContentView(R.layout.splash_screen);
OAuthLogin();
}
});
}
}
private boolean isAuthenticated() {
String token = prefs.getString(Constants.OAUTH_TOKEN, "");
if(token.equals(""))
return false;
String secret = prefs.getString(Constants.OAUTH_TOKEN_SECRET, "");
if(secret.equals(""))
return false;
return true;
}
private void OAuthLogin() {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
new AsyncTask<Void,Void,Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
requestToken = twitter.getOAuthRequestToken(Constants.CALLBACK_URL);
authUrl = requestToken.getAuthenticationURL();
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl));
myIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
Log.i(TAG, "open browser");
LoginActivity.this.startActivity(myIntent);
} catch (TwitterException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
private void OAuthLogin(final String token, final String tokenSecret) {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
new AsyncTask<Void,Void,Void>() {
#Override
protected Void doInBackground(Void... params) {
AccessToken accessToken = new AccessToken(token, tokenSecret);
twitter.setOAuthAccessToken(accessToken);
return null;
}
#Override
protected void onPostExecute(Void param) {
goToMainActivity(twitter);
}
}.execute();
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume");
if ((this.getIntent() != null) && (this.getIntent().getData() != null)) {
setContentView(R.layout.splash_screen);
new AsyncTask<Void,Void,Void>() {
#Override
protected Void doInBackground(Void... params) {
Uri uri = LoginActivity.this.getIntent().getData();
afterBrowser(uri);
return null;
}
#Override
protected void onPostExecute(Void uri) {
storeAccessToken();
goToMainActivity(twitter);
}
}.execute();
} else if(!firstTime) {
goToMainActivity(twitter);
}
}
private void afterBrowser(Uri uri) {
String verifier = uri.getQueryParameter("oauth_verifier");
String token = uri.getQueryParameter("oauth_token");
try {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
requestToken = new RequestToken(token, Constants.CONSUMER_SECRET);
accessToken = twitter.getOAuthAccessToken(requestToken,
verifier);
twitter.setOAuthAccessToken(accessToken);
} catch (TwitterException ex) {
Log.e(TAG, "" + ex.getMessage());
}
}
private void storeAccessToken() {
prefs.edit()
.putString(Constants.OAUTH_TOKEN, accessToken.getToken())
.putString(Constants.OAUTH_TOKEN_SECRET, accessToken.getTokenSecret())
.commit();
}
private void goToMainActivity(Twitter twitter) {
firstTime = false;
Intent myIntent = new Intent(this, MainActivity.class);
MyApplication.getInstance().setTwitter(twitter);
startActivity(myIntent);
}
}
if(!firstTime) {
goToMainActivity();
finish();
}
What no history does is that it doesn't let that certain activity register in the stack of past activities, it doesn't allow it to skip parts of the Activity lifecycle.
If you don't want certain code not to execute then you should do something like:
Login Activity:
if(!firstTime) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent. putExtra("skip", true);
finish();
}
Main Activity: (inside onCreate)
if(!getIntent().getBundle().getBoolean("skip", false)) {
//You code that you don't want
}
This is the activity lifecycle I hope it's beneficial to you:
android:noHistory Whether or not the activity should be removed from
the activity stack and finished (its finish() method called) when the
user navigates away from it and it's no longer visible on screen —
"true" if it should be finished, and "false" if not. The default value
is "false". A value of "true" means that the activity will not leave a
historical trace. It will not remain in the activity stack for the
task, so the user will not be able to return to it.
This attribute was introduced in API Level 3.
Quoting the documentation, "it's finish() method called", have you tried finishing the activity yourself?
noHistory = true means once the activity is finish() for that user session, the user will never see it again, however, if the activity is just being paused without finishing, then it will be restarted when going back to it. Before you go to the main activity, just finish() it, if thats your desired behavior.
i am using two activities in twitter android linked app. the first activity is LoginActivity and second is TweetslistActivity. i have used a button in loginActivity and on its click,twitter login dialog opens. when user successfully logs in,then my app should open second activity. but after user is authenticated ,my first activity resumes and i have to click login button again to go to my second activity!
the logcat shows:
08-30 05:05:48.477: I/dalvikvm-heap(4205): Grow heap (frag case) to 6.686MB for 4194320-byte allocation
08-30 05:05:48.557: D/dalvikvm(4205): GC_FOR_ALLOC freed 0K, 3% free 6732K/6920K, paused 76ms, total 76ms
08-30 05:05:49.288: D/gralloc_goldfish(4205): Emulator without GPU emulation detected.
08-30 05:05:55.757: V/tweetsData--(4205): null
08-30 05:06:11.897: E/Twitter Login Error(4205): > No Token available.
i have also used 'android:launchMode="singleTask"' in Manifest file. but it just directs me from first activity to second without login! i am just stuck but didn't get any answer.. pls suggest some good solutions. thank you in advance.
EDIT:
Original code:
public class TwitterLoginActivity extends Activity {
TextView tv;
Button loginBtn;
ImageView logo;
private ConnectionDetector cd;
static Twitter twitter;
ProgressDialog pDialog;
ArrayList<String> tweets;
String tweetsData;
private static SharedPreferences mSharedPreferences;
AlertDialogManager alert = new AlertDialogManager();
RequestToken requestToken;
AccessToken accessToken;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twitter_login);
tweets = new ArrayList<String>();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
alert.showAlertDialog(TwitterLoginActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
return;
}
if (CONSUMER_KEY.trim().length() == 0
|| CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(TwitterLoginActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
return;
}
tv = (TextView) findViewById(R.id.welcome_txt);
loginBtn = (Button) findViewById(R.id.login_btn);
logo = (ImageView) findViewById(R.id.imageView1);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref",
0);
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread th = new Thread(new Runnable() {
public void run() {
loginToTwitter();
}
});
th.start();
}
});
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken);
Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit();
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
}
catch (Exception e) {
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
public void loginToTwitter() {
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(CONSUMER_KEY);
builder.setOAuthConsumerSecret(CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL()))); }
});
}
catch (TwitterException e) {
e.printStackTrace();
}
}
Intent intent = new Intent(TwitterLoginActivity.this, TweetsListActivity.class);
intent.putExtra("tweetsdata",tweetsData);
startActivity(intent);
finish(); }
private boolean isTwitterLoggedInAlready() {
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
#Override
protected void onResume() {
super.onResume();
}
}
Put this code that was at the end of onCreate() to onResume() with my changes:
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken);
Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit();
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
}
catch (Exception e) {
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
if (!isTwitterLoggedInAlready()) {
// Goto TweetsListActivity
Intent intent = new Intent(TwitterLoginActivity.this, TweetsListActivity.class);
intent.putExtra("tweetsdata",tweetsData);
startActivity(intent);
finish();
}
Also be aware that on your code in lines 127-128 these lines are switched:
startActivity(intent);
intent.putExtra("tweetsdata",tweetsData);
After start activity there is no sense to change the intent.
EDIT:
Also noticed this code after startActivity() for the web login, which don't make any sense:
TwitterLoginActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent intent = new Intent(TwitterLoginActivity.this,
TweetsListActivity.class);
intent.putExtra("tweetsdata",tweetsData);
startActivity(intent);
finish();
}
});
Remove this code.
im facing an error in many tutorials out there, now im trying this tutorial and the problem is that when the explorer is opened, and i log in to twitter, when twitter asks to authorize i hit the Sign In Button, but nothing happens, like i said, i have this problem in many tutorials, not only this, what am i doing wrong?
BTW, i added this class to fix the NetworkOnUI Error:
private class Logintw extends AsyncTask<Void, Void, Uri> {
#Override
protected Uri doInBackground(Void... params) {
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Uri.parse(requestToken.getAuthenticationURL());
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Uri result) {
Intent in = new Intent(Intent.ACTION_VIEW, result);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(in
);
super.onPostExecute(result);
}
}
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
TrequestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(TrequestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),"Already Login to twitter!-----", Toast.LENGTH_SHORT).show();
TwitterLogin=true;
checkloginstatus();
}
}
protected void onNewIntent(Intent intent) {
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(TrequestToken, verifier);
// Shared Preferences
mPrefs=getPreferences(MODE_PRIVATE);
Editor e = mPrefs.edit();
// After getting access token, access token secret store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
TwitterLogin=true;
checkloginstatus();
new updateTwitterStatus().execute(username+ " is using http://AllPagesManager.com , Try it Now!!!");
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
I'm trying to login on twitter from my android app using Twitter4j library but it crashes when the callback is called... and appears this screen: the page is not disponible
this is my code:
public class TwitterLogin extends Activity {
/** Called when the activity is first created. */
Twitter twitter;
RequestToken requestToken;
/*
* Calls the OAuth login method as soon as its started
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
OAuthLogin();
}
/*
* - Creates object of Twitter and sets consumerKey and consumerSecret
* - Prepares the URL accordingly and opens the WebView for the user to provide sign-in details
* - When user finishes signing-in, WebView opens your activity back
*/
void OAuthLogin() {
try {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY,TwitterConstants.CONSUMER_SECRET_KEY);
requestToken = twitter.getOAuthRequestToken(TwitterConstants.CALLBACK_URL);
Log.w("TwitterLogin requestToken callbackUrl: "+requestToken.toString());
// requestToken = twitter.getOAuthRequestToken(OAuth.OUT_OF_BAND);
// String pin = requestToken.getParameter(OAuth.OAUTH_VERIFIER);
String authUrl = requestToken.getAuthenticationURL();
Log.w("TwitterLogin requestToken authUrl: "+authUrl);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
Log.w("TwitterLogin despres del startActivity intent");
} catch (TwitterException ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
Log.e("in Main.OAuthLogin", ex.getMessage());
}
}
/*
* - Called when WebView calls your activity back.(This happens when the user has finished signing in)
* - Extracts the verifier from the URI received
* - Extracts the token and secret from the URL
*/
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.w("TwitterLogin dintre del onNewIntent");
Uri uri = intent.getData();
Log.w("TwitterLogin uri: "+uri.toString());
if (uri != null && uri.toString().startsWith(TwitterConstants.CALLBACK_URL)){
try {
String verifier = uri.getQueryParameter("oauth_verifier");
Log.w("TwitterLogin","onNewIntent oauth_verifier: "+verifier);
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
Log.w("TwitterLogin","onNewIntent accesToken: "+accessToken.toString());
String token = accessToken.getToken(), secret = accessToken.getTokenSecret();
displayTimeLine(token, secret); //after everything, display the first tweet
} catch (TwitterException ex) {
Log.e("Main.onNewIntent", "" + ex.getMessage());
}
}
}
/*
* Displays the timeline's first tweet in a Toast
*/
#SuppressWarnings("deprecation")
void displayTimeLine(String token, String secret) {
if (null != token && null != secret) {
List<Status> statuses = null;
try {
twitter.setOAuthAccessToken(token, secret);
statuses = twitter.getFriendsTimeline();
Toast.makeText(this, statuses.get(0).getText(), Toast.LENGTH_LONG)
.show();
} catch (Exception ex) {
Toast.makeText(this, "Error:" + ex.getMessage(),
Toast.LENGTH_LONG).show();
Log.d("Main.displayTimeline",""+ex.getMessage());
}
} else {
Toast.makeText(this, "Not Verified", Toast.LENGTH_LONG).show();
}
}
}
if someone can help me please, I've been trying to login on Twitter 2 days and I don't know how to solve this.
Thanks
have you provided callback URL for your app when registering you app on twitter.?
if you have provide callback URL then use same in android client...
because you are making request with callback
requestToken = twitter.getOAuthRequestToken(TwitterConstants.CALLBACK_URL);
then server also replies with callback after login is successful to twitter.
public class TwitterActivity extends Activity
{
private Twitter twitter;
private OAuthProvider provider;
private CommonsHttpOAuthConsumer consumer;
String CONSUMER_KEY = "abcdefgh";
String CONSUMER_SECRET = "abcdefgh";
String CALLBACK = "twitterapp://connect";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
askOAuth();
}
private void askOAuth() {
try {
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
provider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize");
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK);
Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
Log.e(APP, e.getMessage());
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(CALLBACK)) {
String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
try {
// this will populate token and token_secret in consumer
provider.retrieveAccessToken(consumer, verifier);
// TODO: you might want to store token and token_secret in you app settings!!!!!!!!
AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
// create a tweet
Date d = new Date(System.currentTimeMillis());
String tweet = "#OAuth working! " + d.toLocaleString();
// send the tweet
twitter.updateStatus(tweet);
} catch (Exception e) {
Log.e(APP, e.getMessage());
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
P.S.: I have used these api's
[1]: https://github.com/punitmg/Twitter-Test-App
[2]: https://github.com/grantland/twitter-android-sdk
[3]: https://github.com/yusuke/twitter4j/
By using all these API's i am able to tweet successfully. But unfortunately the below mentioned 2 screens are appearing in all the above 3 cases..
All i want is to finish() or close the below two screen when my tweet is completed.
So .... plz guide me if i was wrong ...
You need to force login second time to resolve this issue,
So just add the force_login=true in your twitter authorize url.
I mean just change the below line of code in TwitterApp.java class (if you have a class file with different name then search in your project with DefaultOAuthProvider)
mHttpOauthprovider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize?force_login=true");
after adding force_login=true webview loading issue will be resolve but every time you need to enter login and password.