Home>

I want to hide MenuItem with onResume of Activity, but I don't know how.
In onCreateOptionsMenu, it can be realized as per the corresponding source,
onCreateOptionsMenu is only run the first time, so you can use other apps on Google Play
After installing and returning, all other apps will be checked for presence,
I would like to hide it from the menu if everything is already installed.
That control is not possible.

[Added]
Hide menu items
* I tried to fix it with reference to the above, but an error occurs.

Error code

OnResume "MenuItem mItem = menu.findItem (R.id.action_app)"

java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem (int)' on a null object reference
Applicable source code
public class MainActivity extends AppCompatActivity {
    public Menu menu;
    @Override
    public void onResume () {
        super.onResume ();
        // Other app introduction process
        AppOther appOth = new AppOther ();
        // Remove from the menu when all other apps exist
        if (! appOth.appOtherChk ()) {
            MenuItem mItem = menu.findItem (R.id.action_app);
            mItem.setVisible (false);
        }
    }
    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        // Inflate the menu;this adds items to the action bar if it is present.
        getMenuInflater (). inflate (R.menu.menu_main, menu);
        this.menu = menu;
        // Other app introduction process
        AppOther appOth = new AppOther ();
        // Remove from the menu when all other apps exist
        if (! appOth.appOtherChk ()) {
            MenuItem mItem = menu.findItem (R.id.action_app);
            mItem.setVisible (false);
        }
        return true;
    }
Supplemental information (FW/tool version etc.)

Android Studio3.4
API level 14 to 28

  • Answer # 1

    I was able to solve the problem by determining whether menu is null and processing it.
    The first time, onResume seems to move before onCreateOptionsMenu moves, so now it works well by putting this judgment.

    @Override
        public void onResume () {
            super.onResume ();
            if (menu! = null) {
                // Other app introduction process
                AppOther appOth = new AppOther ();
                // Remove from the menu when all other apps exist
                MenuItem mItem = menu.findItem (R.id.action_app);
                if (! appOth.appOtherChk ()) {
                    mItem.setVisible (false);
                } else {
                    mItem.setVisible (true);
                }
            }
        }