Question

I have a ListPreference in the preference system for my Android app to allow a user to select from one of up to 5 different accounts worth of data. Inside the preference they need to be able to switch between the accounts they wish to currently use. The problem though is that when I click on one of the selections, I get the selection from before the list was opened. Code as follows:

    // Get the Account Preferences pointer
    final ListPreference accountPref = (ListPreference) findPreference("accountPref");
    CharSequence[] entries = { "Account 1", "Account 2", "Account 3", "Account 4", "Account 5" };
    CharSequence[] entryValues = { "1", "2", "3", "4", "5" };
    accountPref.setEntries(entries);
    accountPref.setEntryValues(entryValues);
    accountPref.setDefaultValue("1");

    accountPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Log.i("theApp", "Selected = " + accountPref.getValue());
            return true;
        }

    });        

So if I select the third entry in the dialog, the log returns "1". If I then select the 5th one, it returns "3". It seems to be returning the selection before the new selection. How do I go about getting the current selection, not the last one?

Was it helpful?

Solution

If so, it's because you're reading accountPref.getValue(). The value has not been committed yet, it is only committed once onPreferenceChange() returns true. Instead, use the newValue parameter to read what the user has just picked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top