-2

I want my application to delete all preferences when the user logs out and bring up the LoginActivity after exiting the main screen. I've been following the suggestions here. In my way, I get only the default preferences.

The workflow of my app goes this way if it helps:

Login -> Save User Details to Preferences -> Start MainActivity -> Logout -> Clear Preferences -> Start LoginActivity

Is the problem caused by using the default preferences? Or is it because I called finish()? I've tried apply() and commit(). Neither worked. The preferences still exist when I tried accessing them in the LoginActivity. How do I clear my preferences?

private void logout(){
    // clear preferences
    SharedPreferences sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
    sharedPreferences.edit().clear().apply();
    Intent i = new Intent(this, LoginActivity.class);
    startActivity(i); // call LoginActivity and finish this one.
    finish();
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Donovan Keating
  • 1,715
  • 3
  • 17
  • 27

3 Answers3

2

Use commit

SharedPreferences sharedPreferences =  getSharedPreferences("YourKey", MODE_PRIVATE);
sharedPreferences.edit().clear().commit();
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
sasikumar
  • 12,540
  • 3
  • 28
  • 48
2

Problem is that you are using getPreferences() instead of getSharedPreferences() or getDefaultSharedPreferences().

getPreferences() Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying ContextWrapper.getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.

Since, getPreferences() uses class name as it's preference file name, thus you are inserting in one Activity pref file, and clearing another one.

See this for more detail: https://developer.android.com/reference/android/app/Activity#getPreferences(int)

Qasim
  • 5,181
  • 4
  • 30
  • 51
0

I would suggest you to use a library like Easy Prefs to handle Sharedprefrences. It has a method Prefs.clear() so basically this would clear all the shared prefs. This would make it pretty easy for you to handle sharedPrefs.

Alternatively you can clear sharedpref by the following function-:

public void clearPrefs(){
    SharedPreferences mySPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = mySPrefs.edit();
    editor.clear();
    editor.apply();
}
Abhishek Dubey
  • 937
  • 8
  • 11