Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get document ID of item from FirestoreRecyclerAdapter?

I can query Firestore and get IDs manually, but I'm using FirestoreRecyclerAdapter because it comes with a ton of additional work done out of the box. So, if I have code like this:

FirebaseFirestore db = FirebaseFirestore.getInstance();

Query query = db.collection(COLLECTION_NAME)
        .whereEqualTo("userId", USER_ID)
        .limit(LIMIT);

FirestoreRecyclerOptions options = new FirestoreRecyclerOptions
        .Builder<SomeEntity>()
        .setQuery(query, SomeEntity.class)
        .build();

FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<SomeEntity, MyHolder>(options) {
    @Override
    public void onBindViewHolder(MyHolder holder, int position, SomeEntity model) {
        // I need model ID here
    }
}

So, if I use FirestoreRecyclerAdapter, it automatically deserializes my SomeEntity class into model object. This is all fine and dandy, but now I need to attach listeners to the list, and react with model ID. Now, if I was manually deserializing objects from Firestore I'd do something like this:

for (DocumentSnapshot document : task.getResult()) {
    SomeEntity entity = document.toObject(SomeEntity.class).setId(document.getId());
    list.add(entity);
}

But, since FirestoreRecyclerAdapter is doing deserialisation for me, I don't get to call document.getId() myself. And by the time I'm in onBindViewHolder method, I don't have access to document ID anymore. Is there some method I'm missing, some way to retrieve IDs from adapter that I overlooked?

Note, I do not consider redundantly storing IDs as a field a solution. I will rather inherit and override FirestoreRecyclerAdapter instead, but I'd prefer if I could solve this without that much work.

like image 463
Davor Avatar asked Apr 07 '18 14:04

Davor


1 Answers

When you need the document ID, you should know something already about the item you're dealing with. Typically this will be the position of the item in the list. I.e. when the user clicks on an item, the click handler is passed the ID of that item. If you have the position, you can get the DataSnapshot from the adapter with:

adapter.getSnapshots().getSnapshot(position);

So if you want to get the ID, you'd get it with:

String id = adapter.getSnapshots().getSnapshot(position).getId();
like image 198
Frank van Puffelen Avatar answered Oct 19 '22 20:10

Frank van Puffelen