I need to add Preferences dynamically to my PreferenceActivity and I do it like this:
mFilterShow = (PreferenceScreen)getPreferenceScreen().findPreference("orderScreen");
public void assignmentFieldsAdd()
{
CheckBoxPreference cb1 = new CheckBoxPreference(this);
cb1.setTitle("Detailed explanation " + "\r\n" +"required");
cb1.setKey("assign1");
CheckBoxPreference cb2 = new CheckBoxPreference(this);
cb2.setTitle("Shoot exclusive video");
cb1.setKey("assign2");
CheckBoxPreference cb3 = new CheckBoxPreference(this);
cb1.setKey("assign3");
cb3.setTitle("Shoot common video");
mFilterShow.addPreference(cb1);
mFilterShow.addPreference(cb2);
mFilterShow.addPreference(cb3);
}
and then, I need to delete it on some event. When I call
public void assignmentFieldsDelete()
{
mFilterShow.removePreference(mFilterShow.findPreference("assign1"));
mFilterShow.removePreference(mFilterShow.findPreference("assign2"));
mFilterShow.removePreference(mFilterShow.findPreference("assign3"));
}
I get an
02-05 18:14:50.159: E/AndroidRuntime(15259): FATAL EXCEPTION: main
java.lang.NullPointerException
at com.assignmentexpert.AssignmentPref.assignmentFieldsDelete(AssignmentPref.java:175)
at com.assignmentexpert.AssignmentPref$2.onPreferenceChange(AssignmentPref.java:97)
at android.preference.Preference.callChangeListener(Preference.java:756)
at android.preference.ListPreference.onDialogClosed(ListPreference.java:219)
at android.preference.DialogPreference.onDismiss(DialogPreference.java:389)
at android.app.Dialog$ListenersHandler.handleMessage(Dialog.java:1047)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
so it can't find preference which I created dynamically. The same thing occurs when I simply want to call getPreferenceScreen().findPreference("assign1").getTitle();
How can I resolve this?
I didn't find accurate solution to my question. It's quite weird that I can't delete or even find Preferences which I added dynamically to my PreferenceScreen. In both cases I've got NullPointerException.
But I find solution which solved my issue. I created 2 separated xml preferences with all required elements. I add and remove them on corresponding events.