我需要将 Preferences 动态添加到我的 PreferenceActivity 中,我这样做:
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);
}
然后,我需要在某些事件中删除它。当我打电话
public void assignmentFieldsDelete()
{
mFilterShow.removePreference(mFilterShow.findPreference("assign1"));
mFilterShow.removePreference(mFilterShow.findPreference("assign2"));
mFilterShow.removePreference(mFilterShow.findPreference("assign3"));
}
我得到一个
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)
所以它找不到我动态创建的偏好。当我只想打电话时也会发生同样的事情getPreferenceScreen().findPreference("assign1").getTitle();
我该如何解决这个问题?