Search code examples
javaandroidandroidx

ClassCastException: HeaderViewListAdapter cannot be cast to MenuAdapter in Android when using a ContextMenu with a header title


The above error occurs when I long click on a list item in a ListView and I have registered a context menu that will then show up and the user can choose an option.

I get no errors on an actual device, but on the emulator (API level 25) I now that the error above. In the stack trace there is no reference to my own code, but to it comes from the MenuPopupWindow line 141 as can be seen below (this is an Android predefined class, not my class). When I look in that file in the Android sources there is this line:

((MenuAdapter) getAdapter()).getAdapterMenu().close(false /* closeAllMenus */);

which seems to cause the exception below:

E/UncaughtException: java.lang.ClassCastException: android.widget.HeaderViewListAdapter cannot be cast to com.android.internal.view.menu.MenuAdapter at android.widget.MenuPopupWindow$MenuDropDownListView.onKeyDown(MenuPopupWindow.java:141)

I have checked that there are no problems in my onCreateContextMenu method in the calling fragment- the crash happens AFTER execution of onCreateContextMenu has finished.

I have no had any problems like this previously either on the emulator or on a real device, but this only happened after upgrading the UI libraries to androidx libraries.

So I am wondering if that has anything to do with it (but it works with no problems on a real device. Since the problem happens in an internal Android class I kind of have no idea how to fix this or if this is something to do with my code in any way or if it is an internal Android bug?

Update: When I leave out the following line it does not crash on the emulator (but then I get no header for my context menu obviously):

menu.setHeaderTitle("Tournament options");

Where the menu comes from inside the overridden method:

public void onCreateContextMenu(ContextMenu menu, View v,
                                ContextMenu.ContextMenuInfo menuInfo) 

Also, I do not get this error on an emulator running API 29. The device I tested it on runs API 28. Since I don't have a real device with API 25 (on which it crashes on the emulator), I am not sure whether it would crash or not on a real device with API 25. But of course, it is worrying that the emulator API 25 crashes.

Any help appreciated.


Solution

  • Well, I cold rebooted the emulator and then there were no problems on any API level. Just thought I would post it as an answer in case any other stumbles into this problem. Must be an emulator software bug on API level 25.