Nidhin_toms
Nidhin_toms

Reputation: 737

onOptionsItemSelected issue

i have created an options menu for my database class. Upon launching the options menu, I would like to the desired activity at the click of the specified button.

But the issue is that if i click on any option , i get directed to the MainMenu.class . Any ideas why this is happening ?

code:

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        new MenuInflater(this).inflate(R.menu.optionmenu, menu);
        return(super.onCreateOptionsMenu(menu));
    }


    public boolean onOptionsItemSelected ( MenuItem item){
        switch (item.getItemId())
        {
        case R.id.item1:
        { Intent r=new Intent(Database.this,MainMenu.class);
            startActivity(r);
        }

        case R.id.takesurvey:
        { 
            Toast toast=Toast.makeText(this, "check", 2000);
               toast.show();
            Intent r1=new Intent(Database.this,SurveyActivity.class);
            startActivity(r1);
        }

        case R.id.viewstats:
        { Intent r2=new Intent(Database.this,Stats.class);
            startActivity(r2);
        }

        case R.id.changesort:
        { Intent r3=new Intent(Database.this,MainMenu.class);
            startActivity(r3);
        }

        case R.id.menuexit:
        { Intent r4=new Intent(Database.this,MainMenu.class);
            startActivity(r4);
        }
        }
        return true;
    }

Upvotes: 1

Views: 5298

Answers (3)

CChi
CChi

Reputation: 3134

It looks like you are missing a break statement in every case.

Upvotes: 9

Shankar Agarwal
Shankar Agarwal

Reputation: 34765

 public boolean onOptionsItemSelected ( MenuItem item){
        switch (item.getItemId())
        {
        case R.id.item1:
        startActivity(new Intent(Database.this,MainMenu.class));
        break;

        case R.id.takesurvey:
        Toast.makeText(this, "check", 2000).show();
        startActivity(new Intent(Database.this,SurveyActivity.class));
        break;

        case R.id.viewstats:
        startActivity(new Intent(Database.this,Stats.class));
        break;

        case R.id.changesort:
        startActivity(new Intent(Database.this,MainMenu.class));
        break;

        case R.id.menuexit:
        startActivity(new Intent(Database.this,MainMenu.class));
        break;

        return true;
    }

Upvotes: 4

Shubhayu
Shubhayu

Reputation: 13552

For each of your conditions in the Switch statement in onOptionsItemSelected() you must return true. If you handle the case then you must return true, if you don't then you should call the super class implementation of it.

case R.id.item1:
    { Intent r=new Intent(Database.this,MainMenu.class);
        startActivity(r);
        return true;
    }

Go through this for more details http://developer.android.com/guide/topics/ui/menus.html#options-menu

Upvotes: 1

Related Questions