eular eular - 1 month ago 15
Android Question

SharePreferences, gets the value in debug mode but not in run mode

I am testing an app. Login twitter and and then logout.
When logout, logout method runs(inside Settings/Options menu of MainActivity),and i clear sharedPreferences and return to loginActivity.

In loginActivity(onCreate), with putBoolean, i set the boolean value as true.
From loginActivity, with a botton click i go to MainActivity. In mainActivity, i get the value as false(the default value).
But, when I debug my app line by line, my sharedPreferences.getBoolean("xxx",false) method returns true.

I guess code is running so fast and blocking I/O causes sharedPreferences not to be able to get the true value in LoginActivity.

How can I solve this ?

See code blocks below, if needed:

public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
setContentView(R.layout.activity_login);

// Initialize application preferences
mSharedPreferences = getSharedPreferences(Constants.PREF_NAME, 0);

loginButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
// ...

isLoggedIn = true;

// Save tokens and user info
saveTwitterInfoSharedPref(session,isLoggedIn);

goToMainActivity(consumerKey,consumerSecret);

}


private void saveTwitterInfoSharedPref(TwitterSession session, boolean isLoggedIn) {

long userID = session.getUserId();

/* Storing oAuth tokens to shared preferences */
final Editor e = mSharedPreferences.edit();
e.putBoolean(Constants.TWITTER_LOGIN_STATUS, isLoggedIn);

// Get UsersService via TwitterApiClient to get User object
MyTwitterApiClient myTwitterApiClient = new MyTwitterApiClient(session);
Call<User> user = myTwitterApiClient.getUsersService().show(userID, null, true);

user.enqueue(new Callback<User>() {
@Override
public void success(Result<User> result) {
String userProfileImgURL = result.data.profileImageUrlHttps;
e.putString(Constants.PREF_USER_PROFILE_IMG_URL,userProfileImgURL);
e.commit();
}

@Override
public void failure(TwitterException exception) {

}
});


In MainActivity:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.itemMenuSignOut :
SharedPreferences mSharedPreferences = getSharedPreferences(Constants.PREF_NAME, 0);
TwitterLogOut logOut = new TwitterLogOut();
logOut.logoutTwitter(getApplicationContext(),mSharedPreferences);
startActivity(new Intent(MainActivity.this,LoginActivity.class));
this.finish();
break;
}
return true;
}


TwitterLogOut.class :

public class TwitterLogOut {

public void logoutTwitter(Context context, SharedPreferences sharedPreferences) {
TwitterSession twitterSession = TwitterCore.getInstance().getSessionManager().getActiveSession();
if (twitterSession != null) {
Twitter.getSessionManager().clearActiveSession();
Twitter.logOut();
ClearSharedPref(sharedPreferences);
}
}

public static void ClearSharedPref(SharedPreferences mSharedPreferences){
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.clear();
editor.commit();
}
}

Answer

I think you should move this line :

  goToMainActivity(consumerKey,consumerSecret);

into the success method in saveTwitterInfoSharedPref, like this :

user.enqueue(new Callback<User>() {
        @Override
        public void success(Result<User> result) {
            String userProfileImgURL = result.data.profileImageUrlHttps;
            e.putString(Constants.PREF_USER_PROFILE_IMG_URL,userProfileImgURL);
            e.commit();
            goToMainActivity(consumerKey,consumerSecret);
        }

        @Override
        public void failure(TwitterException exception) {
            // DO something here, like warn the user with a toast
        }
    });

That way, you can be sure that the login was succesful, and that the preference has been saved BEFORE going to MainActivity.

Comments