CHarris
CHarris

Reputation: 2793

Android activity doesn't get started from popup menu

I want to open a new activity, Make_a_contact, from my popup menu. The problem I'm sure is related just to the code below, because when I uncomment the code below - Toast.makeText etc...(and remove the code I want fixed) it works fine.

Thanks for any help!

public void Show_Settings(View v) {
//this is the settings button, whose onclick is identified in menu_thisisatest.xml
    PopupMenu popup = new PopupMenu(this, v);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.menu_thisisatest, popup.getMenu());
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        Intent intent = new Intent(this, Make_a_contact.class);
        return true;
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                Toast.makeText(getApplicationContext(),item.toString(),Toast.LENGTH_SHORT).show();
//            return true;
//        }
    });
    popup.show();
}

Upvotes: 1

Views: 225

Answers (2)

Benjamin Scharbau
Benjamin Scharbau

Reputation: 2089

You need to start your new Activity after generating your intent. Try calling

startActivity(intent);

And, of course, you need to include that code in the onMenuItemClick() method, that is currently commented out in your code, i.e.

@Override
public boolean onMenuItemClick(MenuItem item) {
    Intent intent = new Intent(this, Make_a_contact.class);
    startActivity(intent);
    return true;
}

Upvotes: 3

Onik
Onik

Reputation: 19959

Regarding the comment to @Benjamin Scharbau's answer, when you create intent with new Intent(this, Make_a_contact.class), this is a reference to the anonymous instance of PopupMenu.OnMenuItemClickListener class which isn't inherited from Context (this is the reason for the error). You should use a context in the Intent's constructor, so use the reference to the calling (foreground) Activity, e.g.

Intent intent = new Intent(ClassNameOfCallingActivity.this, Make_a_contact.class)

and pass the intent to the startActivity() method.

Upvotes: 2

Related Questions