AndroidRocket
AndroidRocket

Reputation: 466

How to get the document ID in firestore Android

I trying to get the document id of a document in firestore but i get a random generated id from somewhere i don't know from where it is getting this random id from and why.I trying to query it in the recyclerAdapter my code:

   @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);
        }
    });
}

I tried hard coding the collection name even after that too its getting some random ID!

the log where i click the same item Name but getting different DocumentIDmy console 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

Upvotes: 0

Views: 1714

Answers (2)

Angel
Angel

Reputation: 115

if you add

.document().get()

will always get a new document id

Add this in your onClick method, It will get the exact document 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

Upvotes: 1

Ashutosh Srivastava
Ashutosh Srivastava

Reputation: 323

Replace onClick snippet with below code:

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

Upvotes: 1

Related Questions