In my app i have a button that turns bluetooth on and off, something that i noticed is that when i move the togglebutton defintion to the top of the class and out of onResume(); the app crashes with nullpointerexception, here is the short version of the code that crashes:
public class MainActivity extends Activity {
static final BluetoothAdapter myBluetooth = BluetoothAdapter.getDefaultAdapter();
final ToggleButton tglbtn = (ToggleButton)findViewById(R.id.ToggleButton01);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(myBluetooth == null){
setContentView(R.layout.notsupported);
}
else{
setContentView(R.layout.supported);
}
}
@Override
public void onResume()
{
super.onResume();
tglbtn.setChecked(myBluetooth.isEnabled());
tglbtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) { .......}
}
}
}
When i move final ToggleButton tglbtn = (ToggleButton)findViewById(R.id.ToggleButton01);
back into onResume(), the app works fine and doesn’t crash, can someone explain why this happens?
You are assigning your Views in the onCreate() right? Specifically it should be happening after the setContentView(X). The reason for this is because all views will be non-null at this point.