Java 从Firestore集合(Android)检索文档Id

Java 从Firestore集合(Android)检索文档Id,java,android,firebase,google-cloud-firestore,Java,Android,Firebase,Google Cloud Firestore,我正在尝试提取文档下自动生成的Id,以便在其他地方使用它 以下是完整的代码: mStartChatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final HashMap<String, Object> myChatFields = new HashMap<>();

我正在尝试提取文档下自动生成的Id,以便在其他地方使用它

以下是完整的代码:

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

                }
            });
最后,使用下面的代码行,我尝试将其放入我创建的HashMap中

myChatFields.put("chatCardId", chatId);
我有两个主要问题:

1) 我用来提取文档Id的代码行不起作用,正在提取其他一些新的自动生成的Id(我猜这是因为我在使用.getId()方法之前使用了.document()方法)

2) 此外,由于某种原因,这些信息不会与我最后一行代码一起添加到HashMap中

如何解决这两个问题

更形象地解释一下:


我试图检索“1”并将其添加到“2”区域中。

对于第一部分,您需要在onSuccess函数与void函数中获取文档引用。所以看起来像这样-

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

            }
        });
mWhammyUsersCollection.document(mCurrentUserId).collection(“我的聊天记录”).add(myChatFields)
.addOnSuccessListener(新的OnSuccessListener(){
@凌驾
成功时公共无效(DocumentReference){
字符串chatId=documentReference.getId();
Log.v(“聊天室”,聊天ID);
myChatFields.put(“chatCardId”,chatId);
Intent goToChatActivity=新的Intent(UserProfileActivity.this,
聊天活动(课堂);
星触觉(goToChatActivity);
}
});
1) 我用来提取文档Id的代码行不起作用,正在提取其他一些新的自动生成的Id(我猜这是因为我在使用.getId()方法之前使用了.document()方法)

不,发生这种情况是因为您两次调用CollectionReference的方法:

返回指向此集合中具有自动生成ID的新文档的DocumentReference

因此,每次调用
document()
方法时,都会生成一个新的id。要解决此问题,请更改以下代码行:

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

请看,我使用了引用中第一次生成的
id
。现在在
onSuccess()方法中,您应该使用上面生成的相同
id

myChatFields.put("chatCardId", id);
而不是像您在实际代码中所做的那样更新

2) 此外,由于某种原因,这些信息不会与我最后一行代码一起添加到HashMap中

发生这种情况是因为您使用了错误的引用。使用包含正确
id的引用将解决您的问题。

以书面形式

然而,有时此文档没有有意义的ID,让Cloud Firestore自动为您生成ID更容易。您可以通过调用
add()。


因此,您可以按照@R.Wright answer进行操作。

您可以从采集数据中获取id作为QuerySnapshot。只需存储位置/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());
            }

        }
    });
mFirebaseStore.collection(“allorder”).get().addOnSuccessListener(新OnSuccessListener()){
@凌驾
成功时公共无效(QuerySnapshot QueryDocumentSnapshot){
试一试{
如果(!queryDocumentSnapshots.isEmpty()){
id=queryDocumentSnapshots.getDocuments().get(position.getId();
mArrayList.clear();
List data=queryDocumentSnapshots.toObjects(OrderDetails.class);
mArrayList.addAll(数据);
mcCustomerName.setText(mArrayList.get(position.getCustomerName());
mcCustomerContact.setText(mArrayList.get(position.getContactNumber());
mcCustomerLocation.setText(mArrayList.get(position).getArea().equals(“”?)找不到位置:mArrayList.get(position).getArea());
MCCustomerInstruction.setText(mArrayList.get(position).getSpecialInstruction().equals(“”?)键入:mArrayList.get(position).getSpecialInstruction());
mTotalPrice.setText(mArrayList.get(position.getTotalPrice().equals(“”?)0):mArrayList.get(position.getTotalPrice().toString());
字符串orderStatus=mArrayList.get(position.getOrderStatus();
if(orderStatus.equals(“待定”)| | orderStatus.equals(“拒绝”)){
设置可见性(View.VISIBLE);
}else if(orderStatus.equals(“已接受”)){
mLayout.setVisibility(View.GONE);
}
JSONArray json=newjsonarray(mArrayList.get(position.getItemList());
List mList=new ArrayList();
for(int i=0;i
我尝试过这个方法,但它说“任务中无法应用”忽略了set和add的用法。我已经在上面做了调整。
String id = mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
                .document().getId();
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
                .document(id).set(myChatFields)
                .addOnSuccessListener(/* ... */);
myChatFields.put("chatCardId", 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());
            }

        }
    });