如何在firestore Android中获取文档ID



我试图获取firestore中文档的文档id,但我从某个地方获得了一个随机生成的id,我不知道它是从哪里获得的,也不知道为什么。我试图在recyclerAdapter中查询它我的代码:

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
Log.d(TAG, "onCreateViewHolder: Called");
Glide.with(mContext)
.asBitmap()
.load(mCategoryImages.get(position))
.into(holder.CategoryImageView);
holder.CategoryTextView.setText(mCategoryTittle.get(position));
holder.CategoryTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mFirestore = FirebaseFirestore.getInstance();
// Get the 50 highest items
String id = mFirestore.collection("Categories")
.document("tUdFCajDcQT995jX6G4k")
.collection(mCategoryTittle.get(position))
.document().getId();
Toast.makeText(mContext, id, Toast.LENGTH_SHORT).show();
Log.d(TAG, "onClick: DocumentID: " + id);
}
});
}

即使在那之后,我也努力编码收藏名称——它得到了一些随机ID!

单击相同项目名称但获得不同DocumentID的日志我的控制台2020-04-06 23:23:05.413 21856-21856/?D/CategoryMainListAdapter:onClick:DocumentID:qB79K0LsLllg28pzSyPy2020-04-06 23:23:07.618 21856-21856/?D/CategoryMainListAdapter:onClick:DocumentID:uDumu9NngxsTmtCRuJU2020-04-06 23:23:08.705 21856-21856/?D/类别主列表适配器:点击:文档ID:VmHxk0eUR9mZic5Mrgqc

用以下代码替换onClick片段:

mFirestore.collection("Categories")
.document("tUdFCajDcQT995jX6G4k")
.collection(mCategoryTittle.get(position))
.document().get().addOnSuccessListener(documentSnapshot -> {
String id = documentSnapshot.getId();
});

如果添加

.document().get()

将始终获得一个新的文档id

将此添加到您的onClick方法中,它将获得确切的文档Id。

firebaseFirestore.collection("Categories").document("tUdFCajDcQT995jX6G4k").collection("mCategoryTittle.get(position)").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<QuerySnapshot> task) {
QuerySnapshot snapshot = task.getResult();
assert snapshot != null;
String docId = snapshot.getDocuments().get(position).getId();   // docId is the current document ID

最新更新