尝试在空 object 引用上调用虚拟方法 'void android.widget.Switch.setChecked(boolean)'

Attempt to invoke virtual method 'void android.widget.Switch.setChecked(boolean)' on a null object reference

我已经创建了一个设置 activity,我想用 SharedPreferences 保存切换按钮,但是当我启动 Activity:

时出现错误(见标题)

错误在第 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();

                }
            }
        });

    }

}

谢谢!

你需要做的就是交换这两行(改变它们的顺序):

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

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

你应该先初始化它,然后再使用它。通过这种方式,您尝试访问仍然是 null 的方法,因此 NullPointerException.