如何在Firestore Android中获取文档ID

时间:2020-04-06 18:12:19

标签: android firebase google-cloud-firestore

我试图在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!

我单击相同名称但获得不同DocumentID的日志my console 2020-04-06 23:23:05.413 21856-21856 /? D / CategoryMainListAdapter:onClick:文档ID: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

1 个答案:

答案 0 :(得分:0)

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

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