How to get document id or name in Android in Firestore db for passing on to another activity?

前端 未结 1 557
轮回少年
轮回少年 2021-01-14 05:55

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

相关标签:
1条回答
  • 2021-01-14 06:54

    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()
    
    0 讨论(0)
提交回复
热议问题