Search code examples
androidxmlpersistentpreference

Android XML Preference issue. Can't make it persistent


I have a very simple activity just to show the preference fragment:

public class PreferencesActivity extends Activity {

Fragment frag = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    if (frag == null) {
        // If not, instantiate and add it to the activity
        frag = new PrefsFragment();
        ft.add(android.R.id.content, frag, frag.getClass().getName());
    } else {
        // If it exists, simply attach it in order to show it
        ft.attach(frag);
    }
    ft.commit();
}

private static class PrefsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }

}
}

and preferences.xml with persistent to true:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:enabled="true"
    android:persistent="true"
    android:title="@string/settings" >
    <EditTextPreference
        android:dialogTitle="@string/dialog_ip"
        android:negativeButtonText="@android:string/cancel"
        android:persistent="true"
        android:positiveButtonText="@android:string/ok"
        android:title="@string/ip" />
</PreferenceScreen>

if I open the EditTextPreference, write something, close the dialog and open it again. The value is still there. But that's it... if I click the Back button, and enter the again on the preferences screen, I already lost what was written. If you exit the application also doesn't save.

Am I missing something here?

Running on: Android 4.0.3 Asus TF300


Solution

  • Your EditTextPreference doesn't have a key value. E.g.:

           <EditTextPreference
                android:key="edittext_preference"
                android:title="@string/title_edittext_preference"
                android:summary="@string/summary_edittext_preference"
                android:dialogTitle="@string/dialog_title_edittext_preference" />