Good day. I have a function that determines which item from the menu has been clicked. True faced with an incomprehensible error. I declare the message string at the beginning, and then change it (in accordance with the element on which the click occurred). But at the end of the function, where I want to display a toast, which will show exactly which element the user has clicked, I get an error, saying that I have not initialized the variable. But how did I not initialize it if I changed its value in the process of a function?
PS Everything works if you declare and initialize the variable immediately, i.e.
String.message = "";
I give the code:
public boolean onOptionsItemSelected(MenuItem item) { String message; int id = item.getItemId(); switch(id) { case R.id.menu_item1: message = "menu item 1"; break; case R.id.menu_item2: message = "menu item 2"; break; case R.id.menu_item3: message = "menu item 3"; break; } Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); return true; }
messagevariable, or add thedefaultcondition to the select statement, but it is probably better to simply initialize with an empty string. - I. SmirnovonOptionsItemSelectedmethod, theonOptionsItemSelectedvariable is re-initialized each time, more precisely, it is not initialized, so you should consider the options mentioned above - I. Smirnov