I am trying to create a context menu for a RecyclerView
, which displays a list of Realm results.
I have already registered for context menu in the ViewHolder
constructor, implemented View.OnCreateContextMenuListener
in the ViewHolder class, and implemented it's method. However, i'm getting a NullPointerException
when trying to retrieve an item from the list when context menu is created:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle(entries.get(info.position).getName());
menu.add(0,v.getId(),0,"Delete");
menu.add(0,v.getId(),0,"Cancel");
}
Specifically in this line:
menu.setHeaderTitle(entries.get(info.position).getName());
Keep in mind that "entries" is a list of Realm results of the class "Entry" from my Realm database.
So, apparently I can't access it's position in there. Does anyone know how to deal with this?
This is the error:
java.lang.NullPointerException: Attempt to read from field
'int android.widget.AdapterView$AdapterContextMenuInfo.position'
on a null object reference
at com.example.developer.appname.adapters.EntryAdapter$ViewHolder.onCreateContextMenu(EntryAdapter.java:101)
EDIT:
as EpicPandaForce pointed out, the real null object is not the realm object, but the menuInfo. There are a couple of threads about this problem, like this, this and this, but none seem to provide a solution as they don't have a "best answer", and I tried many of the answers but none work, at least for me. Has you guys dealed with this and effectively solved it? If so please help me out