I have a 2 preferences in my Settings: 1- PreferenceCategory 2-PreferenceX When I press PreferenceX, I add new preferences at runtime into PreferenceCategory. But when I rotate the device or kill my application then reopen it again: I can't find all the new preferences that I have at runtime. I tried to use saveHierarchyState & restoreHierarchyState for the given preferenceCategory but still can't make it work.
Here is a sample for my code:
my preferences.xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="myCat"
android:title="Example list"
android:summary="This list is empty by default" />
<Preference
android:key="button"
android:title="Example button"
android:summary="When clicked this adds an item to the list" />
</PreferenceScreen>
Here is my MainActivity code:
package com.example.testpreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
public class MainActivity extends PreferenceActivity {
private int counter=0;
private PreferenceGroup pg;
/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
pg = (PreferenceGroup) getPreferenceScreen().findPreference("myCat");
getPreferenceScreen().findPreference("button").setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference a_preference) {
Preference preference = new Preference(getApplicationContext());
preference.setTitle("Item" + counter);
preference.setKey("key"+counter);
counter++;
pg.addPreference(preference);
return true;
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
pg.saveHierarchyState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle state) {
if (null != state) {
pg.restoreHierarchyState(state);
}else
super.onRestoreInstanceState(state);
}
}
Try to rotate the device and you will the wrong behavior that I am describing. How can I keep the new preferences that are added during runtime to be shown upon screen rotation?