2

I am doing the android tutorial and in the Adding Actions Buttons part, openSearch() and openSettings() are undefined. So I made them as private voids in the same class. In the switch, though, openSearch(); is apparently unreachable. When I delete that case, the method in the next case is unreachable. Here is my code.

return super.onOptionsItemSelected(item);
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case R.id.action_search:
            openSearch();
            return true;
        case R.id.action_settings:
            openSettings();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
private void openSettings() {
    Toast.makeText(this, "Search button pressed", Toast.LENGTH_SHORT).show();
}
private void openSearch() {
    Toast.makeText(this, "Search button pressed", Toast.LENGTH_SHORT).show();
}
  • `return value;` ends method flow of control, so code after it (in your case `switch`) will not be invoked (is unreachable) – Pshemo Sep 28 '14 at 17:37
  • That is one of the advantages of Android Studio that you yell about unreachable code. – rekire Sep 28 '14 at 17:38
  • 1
    Just as an aside: you should get out of the habit of using resource IDs as case values in a `switch` statement. It will not work in library projects, where resource ID values are not `final`. See [here](http://tools.android.com/tips/non-constant-fields) for more info on this. – Ted Hopp Sep 28 '14 at 17:40

1 Answers1

3

You should get rid of return super.onOptionsItemSelected(item); in the top of your method, or the switch will be never reachable

Blackbelt
  • 156,034
  • 29
  • 297
  • 305