java – Null object reference when flipping screen with SearchView open

Question:

Actually, the essence is described in the title: if you change the screen position while the SearchView is open in the toolbar'е , then the application crashes with an error:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.view.MenuItem.collapseActionView()' on a null object reference

The MenuItemCompat.collapseActionView(searchMenu); method itself written in

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            MenuItemCompat.collapseActionView(searchMenu);

            ...
        }

    });

At the same time, the application does not always crash, but only if a non-default ViewPager'а page is selected. I understand that this is due to the fact that when the screen is flipped, the onCreate method fires again, but onCreateOptionsMenu is called later. If ways to solve the problem?

Answer:

Yes, this is because you are trying to manipulate the menu before it is created.

Here's a workaround for you.

In onPrepareOptionsMenu check the flag (boolean variable shouldCollapseActionView of the activity class, to which you assign the desired value in the right places. In your case, instead MenuItemCompat.collapseActionView(searchMenu); in the ViewPager page change listener.)

Depending on the value of the flag in onPrepareOptionsMenu expand/close searchView

Immediately after changing the value of this variable, call supportInvalidateOptionsMenu() – this will force the menu to be redrawn by calling the onPrepareOptionsMenu method.

So you will always have the menu in the right state and you can safely change it.

Scroll to Top