尝试调用虚方法' void android.widget.Switch.setChecked(boolean)'在null对象引用上

时间:2016-07-10 10:27:03

标签: android sharedpreferences android-sharedpreferences

我已经创建了一个设置活动,并且我希望使用SharedPreferences保存切换按钮,但是当我启动活动时出现错误(请参阅标题):

错误在第13行。

守则:

public class SettingsActivity extends Activity {

    private Switch switchPushNotifications;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        SharedPreferences sharedPreferences = getSharedPreferences("Settings", MODE_PRIVATE);
        switchPushNotifications.setChecked(sharedPreferences.getBoolean("getPushNotifications", true));



        switchPushNotifications = (Switch) findViewById(R.id.switchPush);
        switchPushNotifications.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Log.d("PN", "Push Notifications are currently ON");
                    Pushbots.sharedInstance().setPushEnabled(true);
                    Pushbots.sharedInstance().register();

                    SharedPreferences.Editor sharedPreferencesEditor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
                    sharedPreferencesEditor.putBoolean("getPushNotifications", true);
                    sharedPreferencesEditor.commit();


                }
                else {
                    Log.d("PN", "Push Notifications are currently OFF");
                    Pushbots.sharedInstance().setPushEnabled(false);
                    Pushbots.sharedInstance().unRegister();

                    SharedPreferences.Editor sharedPreferencesEditor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
                    sharedPreferencesEditor.putBoolean("getPushNotifications", false);
                    sharedPreferencesEditor.commit();

                }
            }
        });

    }

}

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要做的就是交换这两行(更改顺序):

switchPushNotifications.setChecked(sharedPreferences.getBoolean("getPushNotifications", true));

switchPushNotifications = (Switch) findViewById(R.id.switchPush);

您应首先初始化它,然后使用它。这样,您就可以尝试访问仍然null的内容以及NullPointerException的内容。

相关问题