N.Preusche N.Preusche - 4 months ago 27
Android Question

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

I have created a settings activity and I want to save the Switch Button with SharedPreferences, but I get a error (see title) when I start the Activity:

The error is in line 13.

The Code:

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();

}
}
});

}

}


Thanks!

Answer

All you need to do is swap these two lines (change their order):

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

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

You should first initialize it, and then use it. This way you're trying to access a method on something that's still null and thus the NullPointerException.

Comments