Question

I have integrated Twitter into my application (using OAuth and twitter4j library) to update status on user's account on behalf of user. This works nice.

Before updating status, I check in Shared Preferences for stored AccessToken. If it is available, i.e. user is logged in, then update the status otherwise user is not logged in and hence display twitter page for user to login.

The problem is that if user has once logged in and hence I have AccessToken in Shared Preferences and now, if user revokes permission from application and I try to post status, then it gives this exception or error.

enter image description here

How do I come to know that user has revoked permission and thus I need to ask for authorization?

EDIT : I come to know how to handle the case of unuthorized access and I handled it. But still this exception is thrown.

Was it helpful?

Solution 2

I solved the issue. The problem was that I was testing on what it does when user unauthorizes the application. And I unauthorized the application from twitter account which I used to create application at dev.twitter.com. Doing this invalidated my accesstoken which was stored in shared preferences and hence in my code when I fetch it from shared preferences and use it, I used to get exception.

The solution is to recreate an accesstoken in application created at dev.twitter.com. And in my code I added this condition :

catch (TwitterException e) {

    if (e.getStatusCode() == -1) {

        // This is the case when the developer who created the application has revoked the application permission.
        // In this case we need to remove stored access token as it is no longer valid.
        // Logging in again will fetch newer accesstoken and will solve the problem.
        logoutFromTwitter();
        loginToTwitter();
    }
}

OTHER TIPS

It might sound weird but try to set your time/date update automatically. Based on my previous experience this was the problem. When i set this and after the phone time is synced, everything works fine.

Then try this :-

// ConfigurationBuilder
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(twitterConsumerKey);
builder.setOAuthConsumerSecret(twitterConsumerSecret);

// Access Token from sharedPreference
String access_token = mSharedPreferences.getString(TwitterConstants.PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret from sharedPreference
String access_token_secret = mSharedPreferences.getString(TwitterConstants.PREF_KEY_OAUTH_SECRET, "");

AccessToken accessToken = new AccessToken(access_token, access_token_secret);
twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName() + " (" + user.getScreenName() + ")";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top