I wanna know why when I declare a member variable and assign it a value linking it with a button, the app keeps crashing. However, when I declared it without a value and gave it the value inside the onCreate method, the app worked perfectly fine.
Crashes when:-
public class MainActivity extends AppCompatActivity {
Button buttonTrue = findViewById(R.id.buttonTrue);
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonTrue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "False", Toast.LENGTH_SHORT).show();
}
});
}
Doesn't Crash when :-
public class MainActivity extends AppCompatActivity {
Button buttonTrue;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonTrue = findViewById(R.id.buttonTrue);
buttonTrue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "False", Toast.LENGTH_SHORT).show();
}
});
}