0

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

Community
  • 1
  • 1
F_Bass
  • 343
  • 4
  • 17
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – P.J.Meisch May 22 '17 at 03:54
  • it says `ContextMenu.ContextMenuInfo menuInfo` is null – EpicPandaForce May 22 '17 at 05:44
  • 2
    @EpicPandaForce you are right. menuInfo is the null object, apparently there are a couple of threads about this problem here on SO, but all of the solutions are incomplete or don't work – F_Bass May 22 '17 at 22:10

0 Answers0