Can't save my Preferences after app killed

2019-05-11 10:32发布

问题:

Hi I'm trying to implement a settings page on my Android App. I defined a xml Preference file, where I implemented CheckBoxPreference and EditTextPreference.

All the settings work perfectly while running the app, but when I kill it I lose all the settings.

Preference.xml file:

<PreferenceCategory android:title="Connection">

    <CheckBoxPreference
        android:title="Auto Log-In"
        android:summary="Auto connect "
        android:key="autoLogIn" 
        android:enabled="true" 
        android:selectable="true"/>

    <EditTextPreference
        android:name="Server"
        android:summary="Change the default server"
        android:defaultValue="www.google.com"
        android:title="Change server to:"
        android:key="www.google.com" />

</PreferenceCategory> 

Preferences.class

public class Preferences extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);\
    }
}

How do I make the app save the settings?

UPDATE: I did some test, and on the Virtual device and on my old HTC Legend with android 2.1 the settings work fine! But they don't work on the Samsung Galaxy S with android 2.2! Does this make sense to anybody?

回答1:

I solved the problem with a soft reset* of my Samsung Galaxy S... can't belive I waisted an all day on a correct code.

Hope this will save some time to others. Marco

*Soft reset: Settings -> Privacy -> Factory data Reset.



回答2:

There shouldn't be any reason for the prefs not to be saved. The prefs are saved immediately when you perform a change (e.g. checking the checkbox).

Are you sure you didn't simply confuse the key with the value? Your server key is android:key="www.google.com" Maybe that's why you think it is not saved?



回答3:

I think you need to set android:persistent="true" for the preferences you want to store in SharedPreferences. As given here.