How to logout Twitter - Twitter4J - android

I want to log out Twitter. I tried to clear reference and request with a new request URI but my account still login. I read this question but it doesn't describe how to login in detail. How to logout Twitter and login with different account? Could you give me some code for logout or relogin?
The function get requet URI
public static String getRequestURI() {
try {
final Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constant.CONSUMER_KEY, Constant.CONSUMER_SECRET);
requestToken = twitter.getOAuthRequestToken(Constant.CALLBACK_URI);
return requestToken.getAuthenticationURL();
} catch (final TwitterException e) {
e.printStackTrace();
}
return "";
}
The function clear reference
public static boolean logout(final Context context) {
getPrefs(context);
CustomSharedPreferences.setPreferences(Constant.ACCESS_TOKEN, "");
CustomSharedPreferences.setPreferences(Constant.ACCESS_TOKEN_SECRET, "");
return true;
}

mTwitter.setOAuthAccessToken(null);
mTwitter.shutdown();
That works, source http://wenchaokong.blogspot.in/2013/03/android-twitter-integration-twitter4j.html

Related

Android: Display public Twitter timeline using OAuth and Twitter4J

So I'm trying to get a list of status objects from a public Twitter timeline ( not my own Twitter timeline or anything that I have admin access to, just a public one from a local organization ) using the Twitter4J library in Android Studio, but I'm getting a little confused by the documentation. I'm running into this error: "Invalid access token format."
I did create a developers account with Twitter and got a consumer key and token, as well as an access token and secret numbers. Those values are saved in a set of private static strings for now. TWITTER_ZOO_ID is a private long with the Twitter ID number for the feed that I want to display. Here's the applicable code that I currently have:
Twitter twitter;
List<Status> statuses = null;
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey( TWITTER_CONSUMER_KEY )
.setOAuthConsumerSecret( TWITTER_CONSUMER_SECRET )
.setOAuthAccessToken( TWITTER_AUTH_TOKEN )
.setOAuthAccessTokenSecret( TWITTER_AUTH_TOKEN_SECRET );
try {
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
twitter.setOAuthConsumer( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET );
statuses = twitter.getUserTimeline( TWITTER_ZOO_ID );
}
catch( TwitterException e ) {
Log.e( "TwitterListFragment", "Twitter Exception" );
return;
}
for( Status status : statuses )
mAdapter.add( status );
If anyone has a link to a good example for Twitter 1.1 using Twitter4J, or can provide an example of how to get those statuses, I'd really appreciate it. I'm currently using Android Studio and including Twitter4J in Gradle from MavenCentral.
Thank you!
EDIT:
Upon further reading, I've added this additional code without success:
twitter.setOAuthConsumer( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET );
AccessToken token = new AccessToken( TWITTER_AUTH_TOKEN, TWITTER_AUTH_TOKEN_SECRET );
twitter.setOAuthAccessToken( token );
If you want to get info from a public Twitter timeline, you can use Application-only Authentication, because the user doesn´t need to login, I think it fits you because you don´t use admin rights.
The application-only auth flow follows these steps:
An application encodes its consumer key and secret into a specially
encoded set of credentials.
An application makes a request to the POST
oauth2/token endpoint to exchange these credentials for a bearer token.
When accessing the REST API, the application uses the bearer token to authenticate.
Because twitter4j has added this feature recently, you should use the last snapshot library.
An example using it:
private ConfigurationBuilder builder;
private Twitter twitter;
private TwitterFactory factory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.init_act_layout);
// setup
builder = new ConfigurationBuilder();
builder.setUseSSL(true);
builder.setApplicationOnlyAuthEnabled(true);
builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
Configuration configuration = builder.build();
factory = new TwitterFactory(configuration);
((MyApp) (MyApp.getApp())).setTFactory(factory);
if (isNeededTwitterAuth()) {
twitter = factory.getInstance();
//Get the token async and save it
}
//Search tweets
}
/*
* Checks if twitter access token is already saved in preferences
*
* #return true if auth needed
*/
private boolean isNeededTwitterAuth() {
SharedPreferences settings = getSharedPreferences(Constants.TWITTER_PREFERENCES, Context.MODE_PRIVATE);
String twitterAccesToken = settings.getString("bearerAccessToken", "");
String twitterTokenType = settings.getString("bearerTokenType", "");
return ((twitterAccesToken.length() == 0) && (twitterTokenType.length() == 0));
}
}
To get the bearer token, do it out of Main UI thread to avoid Network exception, f.i. using AsyncTask:
#Override
protected OAuth2Token doInBackground(Void... params) {
OAuth2Token bearerToken = null;
try {
bearerToken = twitter.getOAuth2Token();
} catch (TwitterException e) {
e.printStackTrace();
}
return bearerToken;
}
When you obtain the bearer token, save it:
SharedPreferences appSettings = getSharedPreferences(Constants.TWITTER_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = appSettings.edit();
prefEditor.putString("bearerAccessToken", result.getAccessToken());
prefEditor.putString("bearerTokenType", result.getTokenType());
prefEditor.commit();
And to use the bearer token:
OAuth2Token bearerToken = new OAuth2Token(bearerTokenType, bearerAccesstoken);
twitter.setOAuth2Token(bearerToken);
And search tweets (always out of Main thread):
#Override
protected QueryResult doInBackground(Void... params) {
twitter.setOAuth2Token(bearerToken);
Query query = new Query();
[...]
result = twitter.search(query);
A complete explanation in the blog (in Spanish...)
And a complete example in the twitter4j github
Hope it helps!
I would recommend using the recently updated Twitter SDK (Fabric).
https://docs.fabric.io/android/twitter/twitter.html

Android, Twitter4j, REST 1.1 - How do I finish the OAuth Process?

I have been at this since the weekend and I am at an impasse. I am pretty new to programming and suspect I am in over my head because I have read every link under "Similar Questions" and it either does not apply or confuses me more.
I am using the Twitter4j API and I worked from code sample no. 7 on the twitter4j website on OAuth support at http://twitter4j.org/en/code-examples.html.
As a skill-building project, I want to make an Android celebrity fan app that will download the timeline from the celebrity's public account. The goal is to execute a timeline download of all the tweets. I do not want the user to login to Twitter with this app or post tweets. The app just downloads a timeline in the background and displays the tweets, probably in a list view.
My code is not executing the following line. It seems to just hang there waiting for something to happen.
RequestToken requestToken = twitter.getOAuthRequestToken();
I have internet permissions in manifest. At this point, I am so confused, I do not even know if I have registered my app correctly. I have the four keys (consumer, consumer secret, access, and access secret).
Settings
-Website: made something up
-Application Type: Read Only
-Callback URL: left it blank
-I did not opt in to "Sign In With Twitter."
OAuth Tool
-Request Type: GET
-Request URI: https://api.twitter.com/1/ (probably wrong)
This is my code:
public class TwitterActivity extends Activity
{
Button mButtonTweets;
String JSONString = null;
TextView JSONContent;
class GetTwitterTimeline extends AsyncTask<Void, String, String>
{
#Override
protected String doInBackground(Void... params)
{
try
{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("")
.setOAuthConsumerSecret("")
.setOAuthAccessToken("")
.setOAuthAccessTokenSecret("");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try
{
RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null;
while (accessToken == null)
{
onProgressUpdate(requestToken.getAuthenticationURL());
try
{
accessToken = twitter.getOAuthAccessToken();
}//try
catch(TwitterException te)
{
if (te.getStatusCode() == 401)
{
onProgressUpdate("Unable to get the access token");
}//if
else
{
te.printStackTrace();
}//else
}//catch
}//while
onProgressUpdate("Got Access Token");
onProgressUpdate("Access Token: " + accessToken.getToken());
onProgressUpdate("Access Token Secret: " + accessToken.getTokenSecret());
}//try
catch (IllegalStateException ie)
{
if(!twitter.getAuthorization().isEnabled())
{
onProgressUpdate("OAuth consumer key/secret is not set.");
}//if
}//catch
}//try
catch (TwitterException te)
{
te.printStackTrace();
onProgressUpdate("Failed to get timeline");
}//catch
String JSONString = "JSON content will go here";
return JSONString;
}//doInBackground
protected void onProgressUpdate(String logEntry)
{
Log.d("twitter4j", logEntry);
}
#Override
protected void onPostExecute(String jsonString)
{
JSONString = jsonString;
}
}//end inner class
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_twitter);
new GetTwitterTimeline().execute();
JSONContent = (TextView) findViewById(R.id.textview_tweets);
mButtonTweets = (Button) findViewById(R.id.button_tweets);
mButtonTweets.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
JSONContent.setText(JSONString);
}
});
}
}
Twitter API has been updated. So Request URI: https://api.twitter.com/1/ won't work.
Also AFAIK the way you are trying to make the app won't work out. You need some kind of authentication. I also dumped one of my app after this API change. :(
Read the following link:
https://dev.twitter.com/docs/api/1.1/overview

Twitter access token and access secret is returning null exception after changing to twitter api version 1.1 in android?

First I am able to login with twitter button with twitter4j-core jar version 2.1.11 and able to retrieve access token and secret. But after twitter has stopped the functionality of API version 1 I have added new twitter4j-core jar version 3.0.3 with API version 1.1. Now I am not able to retrieve the access token and access secret.
Here is database method where I have stored my access token and access secret.
public static void save(Context context, final OAuthConsumer oAuthConsumer) {
SharedPreference.storeValue(OAuth.OAUTH_TOKEN, oAuthConsumer.getToken(), context);
SharedPreference.storeValue(OAuth.OAUTH_TOKEN_SECRET, oAuthConsumer.getTokenSecret(), context);
}
Another Database method where I am retrieving the stored values as:
public static AccessToken retrieveStoredAccessToken(Context context)
{
String token = SharedPreference.getValueFromStore(OAuth.OAUTH_TOKEN , context);
String secret = SharedPreference.getValueFromStore(OAuth.OAUTH_TOKEN_SECRET, context);
return new AccessToken(token, secret);
}
Now when user clicks the login button it will redirect to method isAuthenticated() where I am retrieve stored access token and secret
public static boolean isAuthenticated(Context context)
{
try
{
AccessToken accessToken = Database.retrieveStoredAccessToken(context); // String token and secret is received null from databse
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
twitter.setOAuthAccessToken(accessToken);
twitter.getAccountSettings();
return true;
}
catch (TwitterException e)
{
System.out.println("Twitter Authenticated : false");
return false;
}
catch(Exception e)
{
System.out.println("Twitter Authenticated : false");
return false;
}
}
Access token returns Null Exception. I am able to login with twitter but session is not stored because of access token and access secret throws null exception.
following jar file use
1) signpost-commonshttp4-1.2.1.1.jar
2) signpost-core-1.2.1.1.jar
3) twitter4j-core-3.0.3.jar
Finally I have figured my problem.
Just need to change these things:
https://api.twitter.com/oauth/authenticate?force_login=true from http://api.twitter.com/oauth/authenticate

twitter4j 401 authentication error persisting AccessToken

I am having a hard time trying to figure out what's going on. I have the typical app structure that spawns one OAuthActivity that takes care of getting a twitter token, then my main application activity uses that token for various twitter-related operations.
My OAuthActivity works. I get an auth token, and the Twitter web screen correctly shows my application name, etc.... Besides, inside that activity, I can send a tweet and it gets published. . This means the OAuthActivity works, the clock is in sync, the token is valid, etc...
But when this OAuthActivity finishes and returns to the calling activity, whenever I try to use that token (recreating it from the persisted key/secret), no matter for what, the operation always fails with a 401, complaining that AuthChallenge reported null... just like if I provided an empty token, but i haven't !!!
Please find attached the source of my OAuthActivity, and the source of how I initialize Twitter Objects in the main activity. Please tell me if you see something wrong.
PD - I have obviously checked that the token values I assign are the same I get !! Also tried different ways of instantiating Twitter, via properties, via builder, via sets .... and nothing changes :(
EDIT-> I found around I have to call "verifyCredentials()" on the new twitter object if I want to reuse a token, but .... no luck! (please find posted exception at the end)
EDIT-2> If I use on both the child activity and the parent
mTwitter=TwitterFactory.getSingleton()
then the twitter object works, but this is not really acceptable for me because It doesnt use persistance, and I would need to authorize the application everytime. Besides, only Twitter object is authorized, TwitterStream keeps throwing exceptions.
Cheers!
Source code of the parent activity, where I try to use an access token obtained in the child activity, listed below. Whatever I try to do with this token always gets the 401.
private void init_twitter(String tok, String sec) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(Conf.OAUTH_CONSUMER_KEY)
.setOAuthConsumerSecret(Conf.OAUTH_CONSUMER_SECRET)
.setOAuthAccessToken(tok)
.setOAuthAccessTokenSecret(sec);
TwitterFactory tf = new TwitterFactory(cb.build());
mTwitter=tf.getInstance();
/** This always fails, even though I call this routine with the
correct token & secret !!! See at the enf of message for an alternate
routine like this one that makes use of verifyCredentials and
also fails. */
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
mTwitter.updateStatus("yello 2");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}).start();
}
SOurce Code of the child OAuthActivity, it apparently works as I get an access token & am able to tweet:
import a lot;
public class TwitterLogin extends Activity {
private final String TAG = "TwitterLogin";
public final static String PREF_KEY_OAUTH_TOKEN="twitter.oauth.token", PREF_KEY_OAUTH_SECRET="twitter.oauth.secret", PREF_KEY_TWITTER_LOGIN="twitter.oauth.login";
private SharedPreferences mPreferences;
private Twitter twitter = new TwitterFactory().getInstance();
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "Starting task to retrieve request token.");
this.mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
super.onCreate(savedInstanceState);
getActionBar().setTitle("TWITTER AUTHENTICATION");
}
private void returnParent(boolean result) {
setResult(result?Activity.RESULT_OK:Activity.RESULT_CANCELED, null);
if (Conf.LOG_ON) Log.d(TAG, "TWITTER AUTH: END PROCESS , GLOBAL RESULT "+result);
/** THE FOLLOWING THING WORKS !!!!! IT SUCCESSFULLY TWEETS */
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
twitter.updateStatus("yello");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}).start();
finish();
}
/**
* Uses TWITTER4J to get the Request URL. It gets something like
* AUTH URL TWITTER4J IS http://api.twitter.com/oauth/authorize?oauth_token=xxxxxxxxxxxxxxxxxxxxx
*
* #return The Request URL to open in webview and get the Verifier
*/
private String oauth_twitter4j_getRequestUrl() throws TwitterException {
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
RequestToken tempToken = twitter.getOAuthRequestToken(Constants.OAUTH_CALLBACK_URL);
return tempToken.getAuthorizationURL();
}
#Override
protected void onResume() {
super.onResume();
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
webview.setVisibility(View.VISIBLE);
setContentView(webview);
Log.i(TAG, "Retrieving request token from Google servers");
try {
StrictMode.ThreadPolicy policy = new StrictMode. ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);
String authorizationUrl=oauth_twitter4j_getRequestUrl();
Log.d(TAG, "AUTH URL TWITTER4J IS "+authorizationUrl_t);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (Conf.LOG_ON) Log.d(TAG,"WebView: "+url);
if (url != null && url.startsWith(Constants.OAUTH_CALLBACK_URL)) try {
System.out.println("TWEET TWEET TWEET");
retrieveAccessToken(url); //added this
webView.setVisibility(View.GONE); //added this
return true;
} catch (Exception e) {
e.printStackTrace();
returnParent(false);
return true;
} else return false;
}
private void saveAccessToken(AccessToken accessToken) {
// Shared Preferences
Editor e = mPreferences.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());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit();
Log.e("Twitter OAuth Token", "> " + accessToken.getToken()+"-"+accessToken.getScreenName());
}
private void retrieveAccessToken(String url) throws Exception {
String requestToken = extractParamFromUrl(url,"oauth_token");
String verifier= extractParamFromUrl(url,"oauth_verifier");
if (Conf.LOG_ON) Log.d(TAG, "Tenemos ACCESS TOKEN y VERIFIER :"+requestToken+","+verifier+","+(new Date().toString()));
if (ONLY_TWITTER4J)
retrieveAccessToken_with4j(verifier);
else
retrieveAccessToken_signpost(verifier);
}
private void retrieveAccessToken_with4j(String verifier) throws TwitterException {
AccessToken a=twitter.getOAuthAccessToken(verifier);
saveAccessToken(a);
returnParent(true);
}
private String extractParamFromUrl(String url,String paramName) {
String queryString = url.substring(url.indexOf("?", 0)+1,url.length());
QueryStringParser queryStringParser = new QueryStringParser(queryString);
return queryStringParser.getQueryParamValue(paramName);
}
});
webview.loadUrl(authorizationUrl);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Exception I get when calling VerifyCredentials with the token I'm sure is right:
Received authentication challenge is null
W/System.err(24915): Relevant discussions can be found on the Internet at:
W/System.err(24915): http://www.google.co.jp/search?q=6f0f59ca or
W/System.err(24915): http://www.google.co.jp/search?q=20d0f74e
W/System.err(24915): TwitterException{exceptionCode=[6f0f59ca-20d0f74e 1de2170b-f94dee38], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
W/System.err(24915): at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:192)
W/System.err(24915): at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
W/System.err(24915): at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:89)
W/System.err(24915): at twitter4j.TwitterBaseImpl.fillInIDAndScreenName(TwitterBaseImpl.java:126)
W/System.err(24915): at twitter4j.TwitterImpl.verifyCredentials(TwitterImpl.java:592)
W/System.err(24915): at com.regaliz.helpers.TwitterManager$2.run(TwitterManager.java:140)
W/System.err(24915): at java.lang.Thread.run(Thread.java:856)
W/System.err(24915): Caused by: java.io.IOException: Received authentication challenge is null
W/System.err(24915): at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:397)
W/System.err(24915): at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:345)
W/System.err(24915): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:276)
W/System.err(24915): at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:479)
W/System.err(24915): at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:34)
W/System.err(24915): at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:156)
W/System.err(24915): ... 6 more
This is the function modified to make use of verifyCredentials:
private void init_twitter_2(final String tok, final String sec) throws TwitterException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(Conf.OAUTH_CONSUMER_KEY)
.setOAuthConsumerSecret(Conf.OAUTH_CONSUMER_SECRET);
// .setOAuthAccessToken(tok)
// .setOAuthAccessTokenSecret(sec);
TwitterFactory tf = new TwitterFactory(cb.build());
mTwitter=tf.getInstance();
Log.d(TAG, "init_twitter_2 "+tok+","+sec);
new Thread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
User u;
try {
/** also tried setting token&secret like this, instead of in the builder-->no success */
mTwitter.setOAuthAccessToken(new AccessToken(tok,sec));
u = mTwitter.verifyCredentials();
Log.d(TAG, "User: "+u.getName());
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}).start();
}
There are stupid people, stupid people, stupid people, and then it's me. For one week I've been struggling with the code, tracing Twitter4j, replicating oauths with curl, suspecting of garbage-collected activities, tracing DDMS, calculating hashes on tokens .... only to find I had 2 instances of Conf.OAUTH_CONSUMER_xxxxx with different values.
As the stuff came from constants, and the names were similar, I didn't realized that.
sigh -- 50 reputation points down the toilet!

Verify Twitter app is logged in on Android

My app I'm developing launches the official twitter app new post screen so the user can post a tweet with some extra text added in the intent. I have got this working nicely however things get a little confused if the user is not logged in with the twitter app. The app launches but the user has to sign in, once they've done that the normal twitter screen appears, if they use the back button to get back to my app the new post screen actually appears after hitting back on the twitter feed screen.
Is there any way I can check that a user is actually signed into the twitter app before trying to run the intent?
I think it's a Twitter app internal issue and you can't test for it.
On the other hand you could provide a Dialog warning the user for this matter with a "Do not show this dialog anymore" checkbox so he gets advised and can dimiss forever the Dialog. You could even provide instructions to authenticate insside the Twitter app in this Dialog.
I am using twitter4j lib.
Here I check for the username. If the username is null then there is no user signed in , else I get the username. This user name is available in the access token which I store in shared preference.
username= mySession.getUsername();
username = (username.equals("")) ? "Not logged in" : username;
code for mySession :-
public class MySession {
private SharedPreferences sharedPref;
private Editor editor;
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
private static final String TWEET_USER_NAME = "user_name";
private static final String SHARED = "Twitter_Preferences";
public TwitterSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(AccessToken accessToken, String username) {
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
editor.putString(TWEET_USER_NAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(TWEET_AUTH_KEY, null);
editor.putString(TWEET_AUTH_SECRET_KEY, null);
editor.putString(TWEET_USER_NAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(TWEET_USER_NAME, "");
}
public AccessToken getAccessToken() {
String token = sharedPref.getString(TWEET_AUTH_KEY, null);
String tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
if (token != null && tokenSecret != null)
return new AccessToken(token, tokenSecret);
else
return null;
}
}
Hope this will help you.
Try this function which will in turn returns you true or false.
True : Logged in
False : Not logged in
twitter.getAuthorization() function will throw you an error if it is not logged in by handling this you can find whether user is previously logged in or not.
public static boolean isAuthenticated(SharedPreferences prefs) {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
try {
twitter.getAuthorization();
return true;
} catch (Exception e) {
return false;
}
}
just add these lines in the oncreate() in ur activity
final Session activeSession = Twitter.getInstance().core.getSessionManager().getActiveSession();
if (activeSession != null){
//do someting
}

Categories

Resources