I recently studied the section about handling application preferences with shared preferences and the PreferenceFragment in the Android Developer Documentation and made the following simple example:
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null)
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit()
}
}
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="@string/pref_general_category">
<EditTextPreference
android:key="@id/pref_key_apiBaseUri"
android:title="@string/pref_apiBaseUri_title"
android:defaultValue="@string/pref_apiBaseUri_default"
android:persistent="true"
android:inputType="text"
android:singleLine="true" />
</PreferenceCategory>
</PreferenceScreen>
id pref_key_apiBaseUri
string pref_apiBaseUri_title "Api Base Uri"
string pref_api_baseUri_default "http://acme.com/api/
Straightforward stuff, eh? I started the app, went to the preference menu / activity, the preference fragment got inflated and I clicked on "Api Base Uri". An EditText dialog popped up, I changed "http://acme.com/api" to "http://acme.com/api2" and pressed on OK. Now, as far as I understood the documentation, preferences should get saved automatically into the shared preferences. When I reopen the EditText dialog, I see that my changes are stored.
HOWEVER.. when I close the activity (or the app) and go back to the settings, again, the default value is back, no changes have been made! What can I do to permanently save my settings?
In your settings.xml, you have:
<EditTextPreference
android:key="@id/pref_key_apiBaseUri"
android:title="@string/pref_apiBaseUri_title"
android:defaultValue="@string/pref_apiBaseUri_default"
android:persistent="true"
android:inputType="text"
android:singleLine="true" />
You must specify a string for key, as the docs for android:key say:
This attribute is required for preferences that persist a data value. It specifies the unique key (a string) the system uses when saving this setting's value in the SharedPreferences.
It seems that your pref_key_apiBaseUri is an empty String. Change it to a valid String and move to strings.xml:
<string name="pref_key_apiBaseUri">KEY</string>
then use as:
<EditTextPreference
android:key="@string/pref_key_apiBaseUri"
...
OR keep it as it is, and just add + in front of id tag, which will create id which in turn will be used as key:
<EditTextPreference
android:key="@+id/pref_key_apiBaseUri"
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With