Android’s onCreateContextMenu() called with no ContextMenuInfo

I recently had an exception report from an eeePC using a mouse which caused the following code to give a NullPointerException:

public void onCreateContextMenu(ContextMenu aMenu, View aView, ContextMenuInfo aMenuInfo) {
	AdapterView.AdapterContextMenuInfo theMenuInfo = null;
	try {
		theMenuInfo = (AdapterView.AdapterContextMenuInfo) aMenuInfo;
	} catch (ClassCastException e) {
		return;
	}
	File theFile = myActivity.getListItem(theMenuInfo.position);
	//...snip rest of code...
}{/java]
The only way that theMenuInfo would be NULL in order to cause the NullPointerException is that the passed in aMenuInfo was NULL -- and that is not supposed to be the case.

I am not quite sure how such an event occurred. It could be a result of "right-clicking" on a spot where there is no list item shown, except that the behavior in that case should have not resulted in a context menu since there is no item there at all. While I should not have to protect my code against a NULL being passed in for the required ContextMenuInfo parameter, I have to live in the world that <em>is</em>, not the world of <em>should</em>. Who knows, maybe this is the start of a trend where "right clicking" on the "white space" of a list will pass in NULL for that parameter and cause a completely different menu to popup for quick actions that provide the same functionality as clicking on the Menu button and choosing some deeper submenu from that list. Then again, it is probably just a bug in the OS and will be fixed at a later point in time. Either way, it's best to protect against NULL parameters even if they should never be NULL.

My new code:
[java]public void onCreateContextMenu(ContextMenu aMenu, View aView, ContextMenuInfo aMenuInfo) {
	AdapterView.AdapterContextMenuInfo theMenuInfo = null;
	File theFile = null;
	try {
		theMenuInfo = (AdapterView.AdapterContextMenuInfo) aMenuInfo;
		theFile = myActivity.getListItem(theMenuInfo.position);
	} catch (ClassCastException cce) {
		return;
	} catch (NullPointerException npe) {
		return;
	}
	//...snip rest of code...
}

If you know why the ContextMenuInfo parameter is sometimes NULL, please feel free to share the reason as I know several developers that would be interested in it besides myself.

One thought on “Android’s onCreateContextMenu() called with no ContextMenuInfo

Leave a Reply

Your email address will not be published. Required fields are marked *