FirebaseUI FirestoreRecyclerAdapter-获取DocumentReference以将其删除

时间:2018-07-11 08:57:29

标签: java android firebase google-cloud-firestore firebaseui

Firebase-UI的{​​{1}} RecyclerView删除项目的正确方法是什么?

这是我的方法:

Firestore

为什么new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { deleteItem(viewHolder.getAdapterPosition()); } }).attachToRecyclerView(recyclerView); private void deleteItem(int position) { DocumentSnapshot ds = (DocumentSnapshot) adapter.getSnapshots().getSnapshot(position); DocumentReference document = ds.getReference(); document.delete(); } 返回getSnapshot而不返回Object?对DocumentSnapshot的投射正确吗?

因为适配器已经对数据库中的更改做出反应,所以我不必调用(DocumentSnapshot)notifyDataSetChanged也正确吗?

2 个答案:

答案 0 :(得分:0)

根据您的评论,如果要从数据库中删除项目,则应直接在delete()对象上使用DocumentReference方法。

db.collection("YourCollection").document("DocumentToDelete")
    .delete()
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "DocumentSnapshot successfully deleted!");
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Error deleting document", e);
        }
    });

由于您使用的是Firebase-UI,因此将自动看到此更改,而无需使用此方法调用:

notifyDataSetChanged();

请注意,如果有文档,删除文档不会删除其子集合。

答案 1 :(得分:0)

正确的方法是像这样创建Firebase-UI-Adapter:

public class YourFirestoreAdapter extends 
FirestoreRecyclerAdapter<YourClass, RecyclerView.ViewHolder> {

//complete the method here for the Adapter, like you would a normal Recycle adapter.

然后在onCreateViewHolder方法之后添加一种删除项目的方法(在您的适配器内):

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

然后,只要您要通过从ItemTouchHelper传递位置来删除项目,就从您的活动中调用此方法。

new ItemTouchHelper(new 
 ItemTouchHelper.SimpleCallback(0,
            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder 
 viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            adapter.deleteItem(viewHolder.getAdapterPosition());
        }
    }).attachToRecyclerView(recyclerView);