Skip to content Skip to sidebar Skip to footer

Sharedpreferences Clear/save

Iam trying to make a checker and I want to save a value into SharedPreferences. But i'am not sure if it works This what I do to save the value is : * SharedPreferences prefs =

Solution 1:

To clear SharedPreferences use this

SharedPreferencespreferences= getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editoreditor= preferences.edit();
editor.clear(); 
editor.commit();

Hope this helped you.

Solution 2:

You are not using the same preferences. Take a while to read http://developer.android.com/reference/android/app/Activity.html

In your first activity you are using:

SharedPreferencesprefs= getSharedPreferences("PREFERENCE", MODE_PRIVATE);

And in the other activity clearing you are only using:

SharedPreferencespreferences= getPreferences(0);

Reading the docs:

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

You need to use the same preference name in both activities. So in your second activity, where you do the clearing just use

SharedPreferencespreferences= getSharedPreferences("PREFERENCE", MODE_PRIVATE);

Solution 3:

// save string to SharedPreferences

publicstaticvoidsaveStringToSharedPreferences(Context mContext, String key, String value) {
    if(mContext != null) {
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences("SHARED_PREFERENCES", 0);
        if(mSharedPreferences != null)
            mSharedPreferences.edit().putString(key, value).commit();
    }
}

// read string from SharedPreferences

publicstaticStringreadStringFromSharedPreferences(Context mContext, String key) {
    if(mContext != null) {
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences("SHARED_PREFERENCES", 0);
        if(mSharedPreferences != null)
            return mSharedPreferences.getString(key, null);
    }
    returnnull;
}

// remove from SharedPreferences

publicstaticvoidremoveFromSharedPreferences(Context mContext, String key) {
    if (mContext != null) {
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, 0);
        if (mSharedPreferences != null)
            mSharedPreferences.edit().remove(key).commit();
    }
}

Solution 4:

Simply you can:

getSharedPreferences("PREFERENCE", 0).edit().clear().commit();

Solution 5:

For removing all preferences :

SharedPreferencesmPrefs_delete= context.getSharedPreferences(GeneralFunctions.SETTING_SINGLE_MASTER_CHILD, Context.MODE_PRIVATE);
SharedPreferences.Editoreditor_delete= mPrefs_delete.edit();
editor_delete.clear().commit();

Post a Comment for "Sharedpreferences Clear/save"