简体   繁体   English

如何使用自动生成的文档 ID 从 android 中的 Firestore 中删除项目

[英]How to delete Item from firestore in android with auto-generated document ID

I have a Firestore database with the following structure in a hierarchical form:我有一个分层形式的具有以下结构的 Firestore 数据库:

collection("notes") > document(currentUserId) > collection("mynotes") > document(auto-generated-key) > items...集合(“notes”)> 文档(currentUserId)> 集合(“mynotes”)> 文档(自动生成的键)> 项目...

I have added data to the Firestore as follows:我已将数据添加到 Firestore,如下所示:

   mAuth = FirebaseAuth.getInstance();
   database = FirebaseFirestore.getInstance();
  
   //here scheduleModel is a model class with constructor(String, boolean, String) with getters and 
   //setters for three of them 
   scheduleNoteModel = new ScheduleNote(noteTitle, isImp, strDate);

I have added the note item like this.我已经添加了这样的注释项目。

database.collection("notes").document(mAuth.getUid())
            .collection("mynotes")
            .document() //generated id automatically...
            .set(scheduleNoteModel)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Toast.makeText(getContext(), "data added ...", Toast.LENGTH_SHORT).show();
                    etNoteTitle.setText("");
                    //dismiss (hide) the bottom sheet after adding item
                    BottomSheetScheduleFragment.this.dismiss();

                    //refresh the fragment
                }
            });

The problem is getting that id back while deleting the item.问题是在删除项目时取回该 ID。 I know there are many questions similar to this, some of them were good but I couldn't figure out to solve them.我知道有很多类似的问题,其中一些很好,但我无法解决它们。 I had a look at this link solution but I wasn't able to solve我查看了此链接解决方案,但无法解决

In adapter在适配器中

 holder.deleteNoteIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            deleteNote(noteModel);
        }
    });


Method to delete

    private void deleteNote(ScheduleNote note, int itemPosition, View view) {
    mAuth = FirebaseAuth.getInstance();
    database = FirebaseFirestore.getInstance();

    //getting the doc id of auto-generated code in Firestore.
     String id = database.collection("notes").document(mAuth.getUid()).collection("mynotes").document().getId();

    Toast.makeText(context, "position " + itemPosition + "doc id " + id, Toast.LENGTH_SHORT).show();

    database.collection("notes").document(mAuth.getUid())
            .collection("mynotes")
            //.document("72NMkKY73CXHVN7DFE8W") get that id automatically
            .document(id)
            .delete()
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    //notifyDataSetChanged();
                    Snackbar snackbar = Snackbar.make(view, "Note Deleted successfully", Snackbar.LENGTH_SHORT);
                    snackbar.show();
                }
            });
}

id in the above variable isn't matching the real id.上述变量中的 id 与真实 id 不匹配。 How to get that id?怎么得到那个id?

I basically want two information for this:我基本上想要两个信息:

  1. How to get the document Id before adding it to the Firestore so that I can attach this to my model class and later on delete based on that ID, has any solution?如何在将文档 ID 添加到 Firestore 之前获取文档 ID,以便我可以将其附加到我的 model class 以及稍后根据该 ID 删除,有什么解决方案吗?
  2. Or, just get the document Id by the Model Class that I pass when clicking on the item in RecyclerView?或者,仅通过单击 RecyclerView 中的项目时通过的 Model Class 获取文档 ID?

I actually did a lot of research but couldn't figure it out.我实际上做了很多研究,但无法弄清楚。 Any quick help would be appreciated, thanks.任何快速帮助将不胜感激,谢谢。

It doesn't seem to mee, that you are following this link solution .您似乎没有遵循此链接解决方案 First of all, as also @Frank van Puffelen mentioned in his comment, "document().getId()" will always generate a brand new ID each time is called.首先,正如@Frank van Puffelen 在他的评论中提到的那样,“document().getId()”每次调用都会生成一个全新的 ID。 So you should save that ID into a variable for later use, so you can delete the desired document right from the adapter.因此,您应该将该 ID 保存到一个变量中以供以后使用,这样您就可以直接从适配器中删除所需的文档。 Your "ScheduleNote" class, besides the "noteTitle", "isImp", and "strDate" fields, should also contain a field called "id".您的“ScheduleNote”class,除了“noteTitle”、“isImp”和“strDate”字段外,还应该包含一个名为“id”的字段。 So your declaration class should look like this:所以你的声明 class 应该是这样的:

class ScheduleNote {
    public String noteTitle, strDate, id;
    public boolean isImp;

    public ScheduleNote() {}

    public ScheduleNote(String noteTitle, String strDate, String id, boolean isImp) {
        this.noteTitle = noteTitle;
        this.strDate = strDate;
        this.id = id;
        this.isImp = isImp;
    }
}

Now, in your particular case, the following lines of code for adding the object to Firestore will do the trick:现在,在您的特定情况下,将 object 添加到 Firestore 的以下代码行将起到作用:

CollectionRefference mynotes = database.collection("notes").document(mAuth.getUid())
        .collection("mynotes")
String docId = mynotes.document().getId();

To create an object of "ScheduleNote" type, please use:要创建“ScheduleNote”类型的 object,请使用:

ScheduleNote scheduleNoteModel = new ScheduleNote(noteTitle, strDate, docId, isImp);
//                                                                     ^
//                                                                newly added

To actually write the data to Firestore, please use:要将数据实际写入 Firestore,请使用:

mynotes.document(docId).set(scheduleNoteModel).addOnSuccessListener(/* ... */);
//                 ^

To be able to delete that document, you should use the following lines of code:为了能够删除该文档,您应该使用以下代码行:

database.collection("notes").document(mAuth.getUid())
        .collection("mynotes")
        .document(id)
        .delete(note.id)
        .addOnSuccessListener(/* ... */);

And this is because, the following line generates again a new ID, which is not correct, as you need to use the one that was generated earlier:这是因为,以下行再次生成一个新的 ID,这是不正确的,因为您需要使用之前生成的 ID:

String id = database.collection("notes").document(mAuth.getUid()).collection("mynotes").document().getId();

First of all add document to your collection without any data in it.首先将文档添加到您的集合中,其中没有任何数据。

DocumentReference addedDocRef =database.collection("notes").document(mAuth.getUid())
            .collection("mynotes")
            .document();
log.i("Added document with ID: " + addedDocRef.getId());

Then add document id to your model class for later use.然后将文档 ID 添加到您的 model class 以供以后使用。

Now, set data for document using your model class.现在,使用您的 model class 为文档设置数据。

addedDocRef.set(scheduleNoteModel)

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

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