Search code examples
javaandroidsharedpreferencesandroid-sharedpreferences

SharedPreferences is not updating its value


Below is a snippet of code that i use in my save settings function (DialogFragment):

String orderBy = mOrderBySpinner.getSelectedItem().toString();
String search = mSearchEditText.getText().toString().trim();

SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString(InventoryPreferences.ORDER_BY, orderBy);
editor.putString(InventoryPreferences.SEARCH_TERM, search);
editor.apply();

I then retrieve that data with the following (Activity):

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String orderBy = sharedPrefs.getString(InventoryPreferences.ORDER_BY, "name ASC");
String searchTerm = sharedPrefs.getString(
                InventoryPreferences.SEARCH_TERM,"").trim();

These are my keys:

public static final String ORDER_BY = "orderBy";
public static final String SEARCH_TERM = "search";

Is there any reason as to why it wouldn't update the values when the key is the same?


Solution

  • getActivity().getPreferences(Context.MODE_PRIVATE);
    

    is not

    PreferenceManager.getDefaultSharedPreferences(this);
    

    Use the second line in both methods.

    From the docs: https://developer.android.com/reference/android/app/Activity.html#getPreferences(int)

    Retrieve a SharedPreferences object for accessing preferences that are private to this activity