亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在android Firestore的文檔字段中保存文檔ID?

如何在android Firestore的文檔字段中保存文檔ID?

喵喵時光機 2023-11-10 17:02:55
我能夠將文檔保存到 firestore,但我也想將新保存的文檔 ID 保存到同一個文檔中,我正在嘗試下面的示例,但效果不好 String id = db.collection("user_details").document().getId();                                Map map = new HashMap<>();                               map.put("username", username);                                map.put("email", email);                                map.put("id", id);                                UserRef.document(id).set(map).addOnSuccessListener(new OnSuccessListener<Void>() {                                    @Override                                    public void onSuccess(Void aVoid) {                                        //progressbar invisible;;                                    }                                });
查看完整描述

2 回答

?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

每次您撥打電話時document(),您都會獲得一個新的唯一 ID。因此,請務必只調用一次,這樣您就只處理一個 ID。

首先獲取文檔參考:

DocumentReference ref = db.collection("user_details").document();

獲取其ID:

String id = ref.getId();

然后編寫要發送的數據:

Map map = new HashMap<>();
map.put("username", username);
map.put("email", email);
map.put("id", id);

最后,將該數據放入前面引用的文檔中:

ref.set(map)...


查看完整回答
反對 回復 2023-11-10
?
森林海

TA貢獻2011條經驗 獲得超2個贊

為了能夠將您的 ID 保存在文檔中,您首先需要創建一個文檔。問題是 ID 是在創建文檔的同時創建的。但我們可以首先創建 ID,然后像這樣發送我們的文檔:


val matchRef = mFirestore.collection(FirebaseHelp().USERS).document(user.uid).collection(FirebaseHelp().MATCHES).document() //notice this will not create document it will just create reference so we can get our new id from it

val newMatchId = matchRef.id //this is new uniqe id from firebase like "8tmitl09F9rL87ej27Ay" 

該文檔尚未創建,我們只是有一個新的 id,所以現在我們將此 id 添加到 POJO 類中(或者我猜它是 POKO,因為它是 Kotlin)。


class MatchInfo(

        var player1Name: String? = null,

        var player2Name: String? = null,

        var player3Name: String? = null,

        var player4Name: String? = null,

        var firebaseId: String? = null, //this is new added string for our New ID

)

現在我們創建要上傳到 firebase 的對象:


val matchInfo = MatchInfo(player1?.mName, player2?.mName, player3?.mName, player4?.mName, newMatchId)

或者我們在將對象發送到 firebase 之前設置新的 id


matchInfo.firebaseId = newMatchId

現在我們使用新 ID 將對象發送到 firebase,如下所示:


val matches = mFirestore.collection(FirebaseHelp().USERS).document(user.uid).collection(FirebaseHelp().MATCHES)

matches.document(newMatchId).set(matchInfo) // this will create new document with name like"8tmitl09F9rL87ej27Ay" and that document will have field "firebaseID" with value "8tmitl09F9rL87ej27Ay"



查看完整回答
反對 回復 2023-11-10
  • 2 回答
  • 0 關注
  • 206 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號