[英]How do I add an array of custom objects to a Firestore document field?
我想在文檔中更新或創建一個稱為“標簽”的字段,該字段應包含一個名為“標簽”(“ tag_name”,“ tag_color”)的自定義對象的數組。 要更新或創建這樣的字段,我必須傳遞一個所述對象的數組(不能傳遞單個對象,因為它無效且昂貴)。 我該如何實現? 我嘗試將Tag對象的ArrayList
添加到Hashmap中:
HashMap<String, ArrayList<GenericTagModel>> myObject = new HashMap<>();
ArrayList<GenericTagModel> toArrayList = new ArrayList<GenericTagModel>(usedModels);
myObject.put("tags",toArrayList);
db.collection("users").document(user.getUid()).set(myObject, SetOptions.merge());
但是,所有要做的就是添加一個沒有任何內容的字段:“ tags:[]”
我能做什么?
你得到tags:[]
因為你的toArrayList
空的, 不包含任何GenericTagModel
對象。 要解決此問題,請使用以下代碼行:
HashMap<String, ArrayList<GenericTagModel>> myObject = new HashMap<>();
ArrayList<GenericTagModel> toArrayList = new ArrayList<GenericTagModel>(usedModels);
toArrayList.add(new GenericTagModel("redTag", "Red")); //Populate ArrayList
toArrayList.add(new GenericTagModel("blueTag", "Blue")); //Populate ArrayList
toArrayList.add(new GenericTagModel("greenTag", "Green")); //Populate ArrayList
myObject.put("tags",toArrayList);
db.collection("users").document(user.getUid()).set(myObject, SetOptions.merge());
結果將是一個包含三個GenericTagModel
對象的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.