Reputation: 1396
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.
Upvotes: 5
Views: 3072
Reputation: 44
Use this in OnBindViewHolder
String DocID = Objects.requireNonNull (getCurrentList ()).snapshot ().get (position).getId ();
If you are using items.class you can create a string with with getter and @DocumentID.
private String docID;
@DocumentId
public String getDocID() {
return docID;
}
Then call this in onBindViewHolder
protected void onBindViewHolder(@NonNull @NotNull ViewHolder holder, int position, @NonNull @NotNull Items model) {
model.getDocId();
}
Upvotes: 0
Reputation: 61
holder.itemView.setOnClickListener { v ->
Toast.makeText(v.context, snapshots.getSnapshot(position).id , Toast.LENGTH_SHORT).show()
}
This comes Under BindviewHolder
Upvotes: 0
Reputation: 598728
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();
Upvotes: 9