I am using a FirestoreRecyclerAdapter
.
I\'m able to get each model and attributes of documents. But I want to get the document id.
I tried usin
Use the adapter's getSnapshots()
method:
@Override
public void onBindViewHolder(MainActivity.DealsHolder holder, int position, DealsResponse model) {
// ...
holder.itemView.setOnClickListener(v -> {
DocumentSnapshot snapshot = getSnapshots().getSnapshot(holder.getAdapterPosition());
snapshot.getId();
// ...
});
}
The getId() method returns the document's id, so in collection/myDoc/someField
, myDoc
would be the id.
If you know your data structure in the next activity, you can recreate the reference with that id through the standard firestore.collection("foo").document("bar")
methods. If you're looking for the general solution, I use getPath()
a bunch:
fun Bundle.putRef(ref: DocumentReference) = putString(REF_KEY, ref.path)
fun Bundle.getRef() = FirebaseFirestore.getInstance().document(getString(REF_KEY))
If you want the id in your model, use a custom SnapshotParser
:
val options = FirestoreRecyclerOptions.Builder<DealsResponse>()
.setQuery(query) {
it.toObject(DealsResponse::class.java).apply { id = it.id }
}
.build()