所以我试图在Android Studio中使用Switch切换小部件并且它提供了一个空对象引用,这是我正在使用的代码。
`import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
public class ProfileActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
TextView username;
Switch sw1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sw1 = (Switch)findViewById(R.id.switch1);
final String usersUsername = getIntent().getExtras().getString("username");
Log.d("USERNAME",usersUsername);
setContentView(R.layout.activity_profile);
username=(TextView)findViewById(R.id.userNameTxt);
username.append(usersUsername);
sw1.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (sw1.isChecked()){
AlertDialog.Builder dialog = new AlertDialog.Builder(ProfileActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Turn on notifications");
dialog.setMessage("Are you sure you want to turn notifications on?" );
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//Action for "OK".
sw1.setChecked(true);
}
});
dialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
sw1.setChecked(false);
}
});
}
else {
sw1.setChecked(false);
}
}
}
当我尝试运行此操作时出现此错误:Attempt to invoke virtual method 'void android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
我不知道如何为对象设置任何内容以使其无效,我做错了什么?