So, I am trying to do an application which gets a random number between 1 and 4 ( 1 inclusive and 4 exclusive ) and after, getting that number, it would change the background color of my Main Activity to the related number:
If it gets the number 1: Change to Blue If number 2: Change to Black If 3: Change to Yellow
Here's the code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
Button button2 = (Button) findViewById(R.id.button2);
button.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
Random rnd = new Random();
int random = rnd.nextInt(1 - 4);
if (random == 1) {
layout.setBackgroundColor(Color.BLUE);
} else if (random == 2) {
layout.setBackgroundColor(Color.BLACK);
} else {
layout.setBackgroundColor(Color.YELLOW);
}
}
}
);
}
The code seems fine to me and Android Studio doesn't report any errors ( only a warning because of the button2 ), but everytime I tap the button, the app just closes and says "Unfortunatly, Exercise has stopped."
My question is: Why does the application stop working after I tap the button?
( If any more information is needed, tell. I never asked and I am quite a novice in asking and Android Development )