Search code examples
androidsharedpreferencesandroid-preferencespreferenceactivity

PreferenceActivity error: doesn't show selected option after close Activity


The value is saved well in SharedPreference when i push it , but it doesn't show when i open another time the PreferenceActivity. It runs if i don't put the android:entryValues , but i can't use it cause there is some difference using distinct languages in order to see what's the value of the prefference.

¿Any idea of what can i do?

Thanks for reading.

code:

the PreferencesMenu activity:

public class PreferencesMenu extends PreferenceActivity  
{
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
     super.onCreate(savedInstanceState);
     setDefaultKeyMode(MODE_PRIVATE);

     addPreferencesFromResource(R.layout.preferences);
     getPreferenceManager().setSharedPreferencesName("Gat_Preferences");

 }
}  

some of strings.xml:

    <string-array name="menu_preference_general_order_array">
        <item>Default</item>
        <item>Alphabetical</item>
    </string-array>     
    <string-array name="menu_preference_general_order_values">
        <item>default</item>
        <item>alphabetical</item>
    </string-array>

preferences.xml layout:

<?xml version="1.0" encoding="utf-8"?>
  <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
     ...
<PreferenceCategory android:title="@string/menu_preference_general">
    <ListPreference 
        android:key="list_order"
        android:persistent="true"
        android:title="@string/menu_preference_general_order_title"
        android:summary="@string/menu_preference_general_order_description"
        android:entries="@array/menu_preference_general_order_array"
        android:entryValues="@array/menu_preference_general_order_values"/> 
    </PreferenceCategory>  
</PreferenceScreen>

mod :

I use android 2.1 , and i can't use the new fragments preference.


Solution

  • You need to tell the preference API what file name you want to use before loading everything up.

    Instead of this:

     addPreferencesFromResource(R.layout.preferences);
     getPreferenceManager().setSharedPreferencesName("Gat_Preferences");
    

    Do this:

     getPreferenceManager().setSharedPreferencesName("Gat_Preferences");
     addPreferencesFromResource(R.layout.preferences);
    

    On a sidenote, don't use R.layout.preferences. You should use R.xml.preferences, putting the file under /res/xml and not under /res/layout. It does work your way, but it's not guaranteed to work in all API versions, since it's not the default way of working with preferences XML files.