AndyAndroid
AndyAndroid

Reputation: 4069

Android: Shared Preference Editor in Preferences class

I have in my main activity access to a shared preference like this:

preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("maxValue", "666");
Boolean test = editor.commit();

when I open my Preference activity I see for that preference the value 666. So that works without issue.

Now I want to do pretty much the same in my Preferences.java, background is that I want to check the input string and notify the user if something is wrong, e.g. I want to make sure that if the users sets the maxValue above 1000, to tell him that this is too high and set it to 899 automatically. I have implemented a change listener:

@Override
public boolean onPreferenceChange(Preference pref, Object newValue) 
{
  if(Integer.valueOf(etAdd.getEditText().getText().toString()) > 899) 
  {
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("maxValue", "899");
    Boolean test = editor.commit(); //test shows true
    Toast.makeText(Preferences.this, "value too high have set it to the maximum of 899", Toast.LENGTH_LONG).show();   //this toast is shown
  }
  return true;
}

When I re-open this preference, even after leaving the preference activity and returning back to it, I see the value the user has entered, e.g. 1000.

anyone an idea?

thanks.

Upvotes: 1

Views: 914

Answers (1)

alexei burmistrov
alexei burmistrov

Reputation: 1417

According to the documentation onPreferenceChange is called BEFORE the changes are written. If you return true (accept new Value), after leaving onPreferenceChange the newValue object is successfully applied and your modifications are ignored. That is the reason of mentioned behavior. Returning false would do the trick.

To project your corrected value to PreferenceActivity immediately, use SetText on your EditTextPreference.

Using typecasted newValue.toString() instead of using contents of the corresponding EditText is also worth considering.

Upvotes: 1

Related Questions