Domanda

I have a list preference with two values and I want to update these two values from with values from another array.

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
     Resources resources = this.getResources();
     String languageData = prefs.getString("languageAlias", " ");
     String[] languageAlias = resources.getStringArray(R.array.languageAlias);
     String[] voiceData = resources.getStringArray(R.array.voiceData);

     int a = 0;
     for(a=0; a<languageAlias.length; a++){
     if(languageData.equals(languageAlias[a]))
     {
         //this is where I have problems
         prefs.edit().putString("voiceAlias", voiceData[2*a]);
         prefs.edit().commit();
         break;
     }

I have been able to get it working up until I have to use the puString command to make the change and commit. Also how do I specify which item in the list preference I want to change, as all I am required to pass to the putString function is a key?

È stato utile?

Soluzione

After this:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

you need to add:

SharedPreferences.Editor editor = prefs.edit();

Then instead of

prefs.edit().putString("voiceAlias", voiceData[2*a]);
prefs.edit().commit();

use

editor.putString("voiceAlias", voiceData[2*a]);
editor.commit();

The documentation on edit() says:

Create a new Editor for these preferences

This means that each time you call prefs.edit() it creates a new Editor object, so when you put string with prefs.edit().putString(...) and when you commit with prefs.edit().commit() you're referencing two new, different Editor objects.

I believe you can also do prefs.edit().putString(...).commit(), but I am not sure if that is possible.

Altri suggerimenti

You cannot write String arrays to your SharedPreferences. You need to change that. You can use

putStringSet (String key, Set values)

but this is available only from API Level 11 onwards. So check that. Or you could convert your array into a single String or into a JSON String (an example I saw elsewhere)

Check out the link below. Is it possible to add an array or object to SharedPreferences on Android

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top