简体   繁体   中英

Retrieving Document Id from Firestore Collection (Android)

I'm trying to extract the auto-generated Id under a document so I can use it elsewhere.

Here is the full code:

mStartChatButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final HashMap<String, Object> myChatFields = new HashMap<>();
            myChatFields.put("dateJoined", ServerValue.TIMESTAMP );
            myChatFields.put("status", "");
            myChatFields.put("snoozeUntil", "");
            myChatFields.put("myCharacter", "");
            myChatFields.put("requestedCustomChatCode", "");
            myChatFields.put("groupChatName", "");
            myChatFields.put("toInviteMembers", "");
            myChatFields.put("lastMessage", "");
            myChatFields.put("lastMessageTimeStamp", ServerValue.TIMESTAMP);

            mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
                    .document().set(myChatFields)
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {

                    String chatId = mWhammyUsersCollection.document(mCurrentUserId)
                            .collection("my-chats").document().getId();

                    Log.v("CHATS", chatId);

                    myChatFields.put("chatCardId", chatId);

                    Intent goToChatActivity = new Intent(UserProfileActivity.this,
                            ChatActivity.class);
                    startActivity(goToChatActivity);

                }
            });

As you can see I'm using the code shown below to generated a Collection called "my-chats" and the .document() is creating the auto-generated document id.

mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
                    .document().set(myChatFields)
                    .addOnSuccessListener(new OnSuccessListener<Void>() {

Then I'm using the line of code shown below to try get the id from that document.

String chatId = mWhammyUsersCollection.document(mCurrentUserId)
                            .collection("my-chats").document().getId();

Finally using the line of code below, I'm trying to put it into the HashMap I have created.

myChatFields.put("chatCardId", chatId);

There are two main problems I am having:

1) The line of code I'm using to extract the document Id is not working and is extracting some other new auto-generated id (I'm guessing it is because I'm using the .document() method before the .getId() method).

2) Also the information for some reason does not get added to the HashMap with the last line of code I put.

How can I solve these two issues?

To explain it a bit more graphically:

Picture of database

I'm trying to retrieve "1" and add it in the area of "2".

1) The line of code I'm using to extract the document Id is not working and is extracting some other new auto-generated id (I'm guessing it is because I'm using the .document() method before the .getId() method).

No, this is happening because you are calling CollectionReference's document() method twice:

Returns a DocumentReference pointing to a new document with an auto-generated ID within this collection.

So every time you are calling document() method, a fresh new id is generated. To solve this, please change the following lines of code:

mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
                .document().set(myChatFields)
                .addOnSuccessListener(/* ... */);

to

String id = mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
                .document().getId();
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
                .document(id).set(myChatFields)
                .addOnSuccessListener(/* ... */);

See, I have used the id that was generated first time inside the refernce. Now inside the onSuccess() method, you should use the same id that was generated above:

myChatFields.put("chatCardId", id);

And not a newer one, as you do in your actual code.

2) Also the information for some reason does not get added to the HashMap with the last line of code I put.

This is happening becase you are using a wrong reference. Using a reference that contains the correct id will solve your problem.

For part one, you'll want to get the document reference in the onSuccess function vs. void. So that would look something like this -

      mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats").add(myChatFields)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
        @Override
        public void onSuccess(DocumentReference documentReference) { 


                String chatId = documentReference.getId();

                Log.v("CHATS", chatId);

                myChatFields.put("chatCardId", chatId);

                Intent goToChatActivity = new Intent(UserProfileActivity.this,
                        ChatActivity.class);
                startActivity(goToChatActivity);

            }
        });

InDocumentation writed that

However, sometimes there is no meaningful ID for this document and it's easier to let Cloud Firestore automatically generate an ID for you. You can do this by calling add().

So you can follow @R. Wright answer.

You can get your id from collection data as QuerySnapshot.Just store the position/id

    mFirebaseStore.collection("allorder").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            try {
                if (!queryDocumentSnapshots.isEmpty()) {
                    id = queryDocumentSnapshots.getDocuments().get(position).getId();
                    mArrayList.clear();
                    List<OrderDetails> data = queryDocumentSnapshots.toObjects(OrderDetails.class);
                    mArrayList.addAll(data);
                    mCustomerName.setText(mArrayList.get(position).getCustomerName());
                    mCustomerContact.setText(mArrayList.get(position).getContactNumber());
                    mCustomerLocation.setText(mArrayList.get(position).getArea().equals("") ? "No Location Found" : mArrayList.get(position).getArea());
                    mCustomerInstruction.setText(mArrayList.get(position).getSpecialInstruction().equals("") ? "Type Something" : mArrayList.get(position).getSpecialInstruction());
                    mTotalPrice.setText(mArrayList.get(position).getTotalPrice().equals("") ? "0" : mArrayList.get(position).getTotalPrice().toString());
                    String orderStatus = mArrayList.get(position).getOrderStatus();
                    if (orderStatus.equals("pending") || orderStatus.equals("rejected")) {
                        mLayout.setVisibility(View.VISIBLE);
                    } else if (orderStatus.equals("accepted")) {
                        mLayout.setVisibility(View.GONE);
                    }
                    JSONArray json = new JSONArray(mArrayList.get(position).getItemList());
                    List<AdminOrderDetailsModel> mList = new ArrayList<>();
                    for (int i = 0; i < json.length(); i++) {
                        JSONObject jsonObject = json.getJSONObject(i);
                        AdminOrderDetailsModel model = new AdminOrderDetailsModel();
                        model.setPackageName(jsonObject.getString("packageName"));
                        model.setPackageType(jsonObject.getString("packageType"));
                        model.setPrice(jsonObject.getString("price"));
                        model.setDuration(jsonObject.getString("duration"));
                        model.setQuantity(jsonObject.getInt("quantity"));
                        mList.add(model);
                    }
                    AdminOrderDetailsAdapter adapter = new AdminOrderDetailsAdapter(getApplicationContext(), mList);
                    setRecyclerLayoutManager(getApplicationContext(), mOrderListView, LinearLayoutManager.VERTICAL);
                    mOrderListView.setAdapter(adapter);

                }
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM