有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

CheckedChangeListener上的java切换按钮,将首选项始终保存为空

我有一个切换按钮,按预期工作。 为了测试我有一个祝酒词,他们都在工作

然而,我试图存储一个切换到共享首选项的值,我一直得到一个关于空对象的错误

我在整个应用程序中都使用了这个SharedReference代码,我从来没有遇到过问题。 但这是我第一次尝试使用切换,其他的都是按钮、收音机或滑块

我错过什么了吗? 如果我注释掉PreferenceManager存储值,它就可以正常工作

以下是我的切换代码:

Switch myToggleButton = inflated.findViewById(R.id.switchon);
myToggleButton.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener()

    {
        @Override
        public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked)
        {
            if(isChecked) {
                preferenceManager.storeValue(packageName, true);
            Toast.makeText(context, "You have Enabled "+ appName + " Notification", Toast.LENGTH_SHORT).show(); }
    else{
                preferenceManager.storeValueapp(packageName, false);
            Toast.makeText(context, "You have DISABLED "+ appName +" Notification", Toast.LENGTH_SHORT).show();
            }
        }
    });

我还尝试通过运行以下命令来双重检查null:

if (myToggleButton!=null){ //run code here }

但这仍然是一样的

这是我按下开关时出现的错误

2020-05-14 12:08:35.360 23783-23783/com.enigamcodes.cutoutnotification E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.enigamcodes.cutoutnotification, PID: 23783
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.enigamcodes.cutoutnotification.Utils.PreferenceManager.storeValue(java.lang.String, java.lang.Object)' on a null object reference
        at com.enigamcodes.cutoutnotification.Settings.NotificationColor$2.onCheckedChanged(NotificationColor.java:133)

共 (1) 个答案

  1. # 1 楼答案

    此消息

    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.enigamcodes.cutoutnotification.Utils.PreferenceManager.storeValue(java.lang.String, java.lang.Object)' on a null object reference

    表示preferenceManager尚未初始化