如何获取在Firestore数据库中的Android文档ID或名称传递到另一个活动?

我正在使用FirestoreRecyclerAdapter

我能够得到每个文件的模型和属性。 但是我想获取文档ID。

我尝试使用model. 自动建议,但没有文件编号或名称

我有以下DealsHolder类。 这是在Kotlin。 然而其余的所有类都在java中。

 package com.guidoapps.firestorerecycleradaptersample import com.google.firebase.firestore.IgnoreExtraProperties @IgnoreExtraProperties data class DealsResponse(var title:String? = null, var price:String? = null, var dealPrice:String? = null, var image:String? = null, var description: String? = null) 

下面我在onCreate()中初始化的函数

  private void getDealsList(){ Query query = db.collection("deals").orderBy("dateTime", Query.Direction.DESCENDING); FirestoreRecyclerOptions response = new FirestoreRecyclerOptions.Builder() .setQuery(query, DealsResponse.class) .build(); adapter = new FirestoreRecyclerAdapter(response) { @Override public void onBindViewHolder(MainActivity.DealsHolder holder, int position, DealsResponse model) { progressBar.setVisibility(View.GONE); holder.textTitle.setText(model.getTitle()); holder.textPrice.setText(model.getPrice()); holder.textDesc.setText(model.getDescription()); holder.textDealPrice.setText(model.getDealPrice()); holder.textPrice.setPaintFlags(holder.textPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); Glide.with(getApplicationContext()) .load(model.getImage()) .into(holder.imageView); holder.itemView.setOnClickListener(v -> { Snackbar.make(DealsList, model.getTitle(), Snackbar.LENGTH_LONG) .setAction("Action", null).show(); }); } 

在这里在holder.itemView onClickListener我想获得文件ID,以传递给另一个活动

然后是以下DealsHolder。

 public class DealsHolder extends RecyclerView.ViewHolder { @BindView(R.id.title) TextView textTitle; @BindView(R.id.thumbnail) ImageView imageView; @BindView(R.id.description) TextView textDesc; @BindView(R.id.price) TextView textPrice; @BindView(R.id.dealPrice) TextView textDealPrice; public DealsHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } 

使用适配器的getSnapshots()方法:

 @Override public void onBindViewHolder(MainActivity.DealsHolder holder, int position, DealsResponse model) { // ... holder.itemView.setOnClickListener(v -> { DocumentSnapshot snapshot = getSnapshots().getSnapshot(holder.getAdapterPosition()); snapshot.getId(); // ... }); } 

getId()方法返回文档的ID,所以在collection/myDoc/someFieldmyDoc就是id。

如果您在下一个活动中知道您的数据结构,则可以通过标准firestore.collection("foo").document("bar")方法重新创建具有该id的引用。 如果你正在寻找一般的解决方案,我使用getPath()一堆:

 fun Bundle.putRef(ref: DocumentReference) = putString(REF_KEY, ref.path) fun Bundle.getRef() = FirebaseFirestore.getInstance().document(getString(REF_KEY)) 

如果你需要你的模型中的id,使用一个自定义的SnapshotParser

 val options = FirestoreRecyclerOptions.Builder() .setQuery(query) { it.toObject(DealsResponse::class.java).apply { id = it.id } } .build()