【问题标题】:How to add a new Sub- Collection in a Firestore document Android如何在 Firestore 文档 Android 中添加新的子集合
【发布时间】:2020-04-06 13:12:45
【问题描述】:

我想将新的子集合添加到现有文档中。我应该创建新的 POJO 类来添加子集合还是任何其他方式来做到这一点。我想将新的子集合添加到现有文档 ID。我是 android 和 Firestore 的新手。提前致谢。this is my Database

我尝试了这个方法,但卡住无法成功

private void setNewCategory(String downloadUrl){
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    DocumentReference newMainCatRef = db
            .collection("HomeFeed")
            .document("5HEkE0ac7sMa7Gjnvf3E")
            .collection("MainCategory")
            .document();
    itemId = newMainCatRef.getId();
    MainCategory category = new MainCategory();

    category.setCategory_id(itemId);
    category.setCategory_name(category_name.getText().toString());
    category.setCategory_url(downloadUrl);
    category.setPriority(priority.getValue());

    newMainCatRef.set(category).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "onSuccess: Success on Updating the new Field to cat");
            FirebaseFirestore NC = FirebaseFirestore.getInstance();
            CollectionReference NewCategory = NC
                    .collection("Categories")
                    .document("tUdFCajDcQT995jX6G4k")
                    .collection(category_name.getText().toString());
            NewCategory.add()

            category_name.setText("");
            priority.setValue(0);
            category_image.setImageResource(R.drawable.ic_android);
            category_progress.setVisibility(View.INVISIBLE);

        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(mContext, "Failed to add New Catgory Try again!", Toast.LENGTH_SHORT).show();
        }
    });

}

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    没有必要做一些特别的事情。正如我在您的代码中看到的,您已经使用了正确的参考:

    CollectionReference NewCategory = NC
                    .collection("Categories")
                    .document("tUdFCajDcQT995jX6G4k")
                    .collection(category_name.getText().toString());
    

    category_name.getText().toString() 是子集合的名称,但问题出现在以下代码行:

    NewCategory.add()
    

    您没有将任何内容作为参数传递。您应该传递自定义对象或 Map 以便能够在数据库中写入内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2018-07-30
      • 2020-08-25
      • 1970-01-01
      相关资源
      最近更新 更多