so I'm trying to use a Switch toggle widget in Android Studio and it is giving a null object reference, this is the code that i am using.
`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);
}
}
}
when I try to run this I get this error: Attempt to invoke virtual method 'void android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
I don't see how I can set anything to the object to not make it null, what am i doing wrong?