设置OnPreferenceClickListener帮助,在活动启动时取消关闭

时间:2011-07-10 16:44:34

标签: java android android-preferences

我知道这不会像我想的那么难。我相信我已经拥有了一切可以实现我的onClickListener的东西。我错过了什么,为什么这个力量关闭?我提供了堆栈来看看。任何帮助都会很棒。这被认为是一个保存用户设置的简单活动。如果我注释掉此代码,则活动会显示活动。

Preference customPref = (Preference) findPreference("customPref");

customPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { //this line forcecloses every time i run the activity.
    @Override
    public boolean onPreferenceClick(Preference preference) {
        Toast.makeText(getBaseContext(),
                       "The custom preference has been clicked",
                       Toast.LENGTH_LONG)
             .show();
        SharedPreferences customSharedPreference = getSharedPreferences(
                "myCustomSharedPrefs", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = customSharedPreference.edit();
        editor.putString("myCustomPref", "The preference has been clicked");
        editor.commit();
        return true;
    }
});

日志:

07-10 16:36:47.137: WARN/System.err(1042): java.lang.NullPointerException
07-10 16:36:47.147: WARN/System.err(1042):     at com.nyneaxis.android.mpg.Preferences.onCreate(Preferences.java:22)
07-10 16:36:47.147: WARN/System.err(1042):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-10 16:36:47.157: WARN/System.err(1042):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
07-10 16:36:47.157: WARN/System.err(1042):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
07-10 16:36:47.157: WARN/System.err(1042):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
07-10 16:36:47.157: WARN/System.err(1042):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
07-10 16:36:47.167: WARN/System.err(1042):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-10 16:36:47.167: WARN/System.err(1042):     at android.os.Looper.loop(Looper.java:123)
07-10 16:36:47.167: WARN/System.err(1042):     at android.app.ActivityThread.main(ActivityThread.java:4363)
07-10 16:36:47.167: WARN/System.err(1042):     at java.lang.reflect.Method.invokeNative(Native Method)
07-10 16:36:47.177: WARN/System.err(1042):     at java.lang.reflect.Method.invoke(Method.java:521)
07-10 16:36:47.177: WARN/System.err(1042):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
07-10 16:36:47.177: WARN/System.err(1042):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
07-10 16:36:47.177: WARN/System.err(1042):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:4)

看起来您的customPref变量为空。确保您在首选项xml(如果使用的话)中具有键customPref的首选项,或者您在那里拼错了键。