I'm very new to developing. I'm building simple android apps as training. Please, consider the following code:
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.menu0:
MenuItem input0 = (MenuItem) findViewById(R.id.menu0);
String string0 = input0.getTitle().toString();
Toast.makeText(this, string0, Toast.LENGTH_LONG).show();
return true;
case R.id.menu1:
MenuItem input1 = (MenuItem) findViewById(R.id.menu0);
String string1 = input1.getTitle().toString();
Toast.makeText(this, string1, Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The aim of this method is to show which one of the two elements of a menu have been pressed by the user, by means of a toast composed by the text contained in the menu elements (as I said, this is just for training ;) ).
The compiler of Android Studio (3.1.2 on Windows) exit with green light (no errors), the apk can be installed on real device but the app crashes (destroyed) when one of the elements of the menu are pressed.
If I change string0
and string1
with an hard coded String, say:
Toast.makeText(this, "Settings", Toast.LENGTH_LONG).show();
the app runs correctly.
Do you have any idea about the reason of this behavior? Thanks!