首页 > 解决方案 > 如何在 Firestore Android 中获取文档 ID

问题描述

我试图在firestore中获取文档的文档ID,但是我从某个我不知道它从哪里获取这个随机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!

我单击相同项目名称但在我的控制台 2020-04-06 23:23:05.413 21856-21856/? D/CategoryMainListAdapter: onClick: DocumentID: qB79K0LsLllg28pzSyPy 2020-04-06 23:23:07.618 21856-21856/? D/CategoryMainListAdapter: onClick: DocumentID: uDumu9NngxsTmtCRuJUs 2020-04-06 23:23:08.705 21856-21856/? D/CategoryMainListAdapter: onClick: DocumentID: VmHxk0eUR9mZic5Mrgqc

标签: androidfirebasegoogle-cloud-firestore

解决方案


用以下代码替换 onClick 代码段:

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

推荐阅读