简体   繁体   English

使用自动生成的 ID 更新 firebase 中的文档

[英]Updating a document in firebase with an auto generated ID

I've learned how to add and delete from Firebase.我已经学会了如何从 Firebase 添加和删除。 It's quite straightforward.这很简单。

My delete code which is activated when clicking the delete button, it's found in my adapter class (it's the only way I could get the delete button click registered correctly)我的删除代码在单击删除按钮时被激活,它在我的适配器类中找到(这是我可以正确注册删除按钮单击的唯一方法)

public void deleteJournal(int position) {
        getSnapshots().getSnapshot(position).getReference().delete();
}

And to add (which is in another class)并添加(在另一个类中)

CollectionReference diaryRef = FirebaseFirestore.getInstance()
                .collection("Diary");
        diaryRef.add(new Diary(growName, description, priority));

But I don't even know where to begin to update.但我什至不知道从哪里开始更新。 I will be putting the edit code in the adapter class which will open a dialog window to edit values.我将把编辑代码放在适配器类中,这将打开一个对话框窗口来编辑值。

I know how to create the window and edit the values and set new variables for this data.我知道如何创建窗口并编辑值并为此数据设置新变量。 But how do I make sure I'm applying this updated data to the document with the corresponding edit button that clicked?但是我如何确保我通过点击相应的编辑按钮将此更新后的数据应用到文档中? Then update Firebase correctly.然后正确更新 Firebase。

diaryRef.add(new Diary(growName, description, priority)).addOnSuccessListener(documentReference -> {
                        String id = documentReference.getId();
                        db.collection("Diary").document(id).update("entryId", id);
                    });

now you will have a unique id to delete or update the entry现在您将拥有一个唯一的 ID 来删除或更新条目

But how do I make sure I'm applying this updated data to the document但是我如何确保我将这个更新的数据应用到文档中

In the same way, you are deleting the document.以同样的方式,您正在删除文档。 Please see the method below:请看下面的方法:

public void updateJournal(int position) {
    Diary diary = getSnapshots().getSnapshot(position).toObject(Diary.class);
    //Make the changes
}

Once you have the Diar y object, you can make the desired updates and then write the document back to the database, as shown in your question.拥有Diar y 对象后,您可以进行所需的更新,然后将文档写回数据库,如您的问题所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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