vancan1ty
vancan1ty

Reputation: 563

Android: updating displayed preferences from SharedPreferences

I'm writing an android app with a preferencesActivity in which selections made in my instance of preferencesActivity affect the values of other preferences items displayed. While I'm able to change the values of the underlying SharedPreferences items pogrammatically, those changed values aren't reflected in the displayed list items until I exit my preferencesActivity and reload it. Below is a stripped down version of my settings class and xml file which illustrate the problem. If a user sets Guitar as the value for the preference with the key instrumentList, I'd like the preference with key tuningChoice to revert to Standard.

//necessary import declarations go here
public class Settings extends PreferenceActivity implements OnSharedPreferenceChangeListener{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        app_preferences.registerOnSharedPreferenceChangeListener(this);
    }

    public void  onSharedPreferenceChanged  (SharedPreferences  sharedPreferences, String  key)   {
        Log.d("onSharedPreferencesChanged", "sharedPreferences changed.  key: " + key);
        Editor preferencesMod = sharedPreferences.edit();
        String instrumentChoice = sharedPreferences.getString("instrumentList", "Guitar");
        if(key.equals("instrumentList")) {
            Log.d("Settings", "key is instrumentList.  chooseTuning before if: " +    sharedPreferences.getString("chooseTuning", "no luck"));
            if(instrumentChoice.equals("Guitar")) {
                preferencesMod.putString("chooseTuning", "Standard");
                preferencesMod.commit(); 
                Log.d("Settings", "chooseTuning after if: " +      sharedPreferences.getString("chooseTuning", "ciao"));
            }
        }
    }
}

xml file preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
        android:title="Settings">
  <ListPreference android:title="Choose an Instrument" android:key="instrumentList" android:entryValues="@array/instruments" android:entries="@array/instruments"/>
        <ListPreference android:title="Choose Tuning" android:key="chooseTuning" android:entryValues="@array/tuningChoices" android:entries="@array/tuningChoices" android:persistent="true"/>
</PreferenceScreen>

I can call addPreferencesFromResource again in my onSharedPreferenceChanged method and that loads a duplicate of all the preferences items, displayed below the old items, with the correct values. If I could figure out some way to cancel out the initial addPreferencesFromResource called during onCreate, I guess I would be set.

Any help would be appreciated, Thanks

Upvotes: 2

Views: 2962

Answers (4)

Rudy Rudy
Rudy Rudy

Reputation: 125

Maybe I am too late for answering this. But, I hope this might help beginner like me.

PackageInfo packageInfo = null;
try {
    packageInfo = preference.getContext().getPackageManager().getPackageInfo(preference.getContext().getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();   

}
preference.setSummary(packageInfo.versionName);

Upvotes: 0

htafoya
htafoya

Reputation: 19273

If anyone comes to this problem, this is the solution:

ListView list = preferenceActivity.getListView();
list.performItemClick(list, 1, list.getItemIdAtPosition(1));

Upvotes: 0

Nick
Nick

Reputation: 6385

I do something along these lines...hopefully it helps:

    ListPreference list = (ListPreference) getPreferenceManager().findPreference("myList");
    list.setValue(sharedPrefs.getString("myList", "default"));
    list.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            sharedPrefs.put("myList", newValue.toString());
            return true;
        }

    });

Upvotes: 1

Nick Campion
Nick Campion

Reputation: 10479

You need to prevent addPReferencesFromResource from running twice? Is this loading your default values? If so, add an additional SharedPreference called DEFAULTS_LOADED and read its value in on create like: (WARNING PSUEDO CODE):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);

    boolean loadDefaults = app_preferences.getBoolean(DEFAULTS_LOADED, true);
    if(loadDefaults)
    {  
        addPreferencesFromResource(R.xml.preferences);
        Editor editor = app_preferences.edit();
        editor.putBoolean(DEFAULTS_LOADED, true);
        editor.commit();
    } 
    app_preferences.registerOnSharedPreferenceChangeListener(this);
}

This will prevent you defaults from being written to the shared preferences every time your activity starts. I assume this is at least a portion of your issue.

Upvotes: 0

Related Questions