从回收者视图和Firebase中删除行

时间:2019-03-02 14:15:49

标签: android firebase firebase-realtime-database

在“回收者”视图中滑动时,我正在尝试从Firebase中删除长尾鹦鹉。我已经设法从“回收者”视图中删除了该记录,但是正在努力从Firebase中删除它。以下是我当前正在使用的方法,但deleteItem()方法(在getSnapshots()方法上(无法解析方法'getSnapshots()')上的adpater中出现错误。

我在回收者视图中使用Item touch助手进行的活动:

 受保护的void onCreate(捆绑保存的InstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_profile);
 Log.d(TAG,“查找recyclerview”);
        recyclerView =(RecyclerView)findViewById(R.id.myRecyclerBooking);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));


        Log.d(TAG,“获取数据库参考”);



        // FirebaseSearch https://www.youtube.com/watch?v=b_tz8kbFUsU
        参考= FirebaseDatabase.getInstance()。getReference()。child(“ Booking”);
        查询firebaseSearchQuery = reference.orderByChild(“ customerID”)。equalTo(mAuth.getCurrentUser()。getUid());

        firebaseSearchQuery.addValueEventListener(new ValueEventListener(){
            @Override
            公共无效onDataChange(@NonNull DataSnapshot dataSnapshot){
                Log.d(TAG,“正在填充recyclerview”);

                list = new ArrayList ();
                对于(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
                    预订b = dataSnapshot1.getValue(Booking.class);
                    list.add(b);
                }
                adapter = new MyAdapterBookings(CustomerProfile.this,list);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }


            @Override
            公共无效onCancelled(@NonNull DatabaseError databaseError){
                Toast.makeText(CustomerProfile.this,“ Opsss ....出问题了”,Toast.LENGTH_SHORT).show();
            }
        });
}

ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new RecyclerItemTouchHelper(0,ItemTouchHelper.LEFT,this);
        新的ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);



        ItemTouchHelper.SimpleCallback itemTouchHelperCallback1 =新的ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP){
            @Override
            public boolean onMove(RecyclerView recyclerView,RecyclerView.ViewHolder viewHolder,RecyclerView.ViewHolder target){
                返回false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder,int direction){
                //从回收者视图中刷行
                //将其从适配器中删除
            }

            @Override
            public void onChildDraw(Canvas c,RecyclerView recyclerView,RecyclerView.ViewHolder viewHolder,float dX,float dY,int actionState,boolean isCurrentlyActive){
                super.onChildDraw(c,recyclerView,viewHolder,dX,dY,actionState,isCurrentlyActive);
            }
        };

        //将触控助手附加到回收者视图
        新的ItemTouchHelper(itemTouchHelperCallback1).attachToRecyclerView(recyclerView);
    }

@Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder,int方向,int位置){

        如果(MyAdapterBookings.MyViewHolder的viewHolder实例){
            //获取删除的商品名称以在小吃店中显示
            字符串名称= list.get(viewHolder.getAdapterPosition())。getMuaName();

            //为撤消目的备份已删除的项目
            最后的预订DeletedItem = list.get(viewHolder.getAdapterPosition());
            最后的int DeletedIndex = viewHolder.getAdapterPosition();

            //从回收者视图中删除该项目
            adapter.removeItem(viewHolder.getAdapterPosition());
            adapter.deleteItem(viewHolder.getAdapterPosition());


            //显示带有“撤消”选项的小吃店
            小吃店小吃店=小吃店
                    .make(coordinatorLayout,“带有” +名称+“已取消的约会!”,Snackbar.LENGTH_LONG);
            Snackbar.setAction(“ UNDO”,new View.OnClickListener(){
                @Override
                public void onClick(View view){

                    //选择撤消,恢复删除的项目
                    adapter.restoreItem(deletedItem,DeletedIndex);
                }
            });
            Snackbar.setActionTextColor(Color.YELLOW);
            Snackbar.show();
        }

    }
 

我的适配器:

  import android.content.Context;
导入android.content.Intent;
导入android.os.Handler;
导入android.support.annotation.NonNull;
导入android.support.v7.widget.RecyclerView;
导入android.util.Log;
导入android.view.LayoutInflater;
导入android.view.View;
导入android.view.ViewGroup;
导入android.widget.Button;
导入android.widget.ImageView;
导入android.widget.RelativeLayout;
导入android.widget.TextView;
导入android.widget.Toast;

导入com.google.android.gms.tasks.OnCompleteListener;
导入com.google.android.gms.tasks.Task;
导入com.google.firebase.database.DataSnapshot;
导入com.google.firebase.database.DatabaseError;
导入com.google.firebase.database.DatabaseReference;
导入com.google.firebase.database.FirebaseDatabase;
导入com.google.firebase.database.Query;
导入com.google.firebase.database.ValueEventListener;
导入com.squareup.picasso.Picasso;

导入java.util.ArrayList;

公共类MyAdapterBookings扩展了RecyclerView.Adapter  {

    上下文上下文;
    ArrayList 预订;
    DatabaseReference参考;
    private静态最终String TAG =“ Bookings Adapter”;
    公共MyAdapterBookings(上下文c,ArrayList  b)
    {
        上下文= c;
        预订= b;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType){
        返回新的MyViewHolder(LayoutInflater.from(context).inflate(R.layout.bookingview,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder持有人,int位置){
        holder.name.setText(bookings.get(position).getMuaName());
        holder.date.setText(bookings.get(position).getDate());
        holder.time.setText(bookings.get(position).getTime());
        holder.price.setText(bookings.get(position).getPrice());
        holder.location.setText(bookings.get(position).getLocation());

    }

    @Override
    public int getItemCount(){
        返回bookings.size();
    }

    类MyViewHolder扩展了RecyclerView.ViewHolder
    {
        TextView的名称,日期,时间,价格,位置;
        公共RelativeLayout viewBackground,viewForeground;
        公共MyViewHolder(查看itemView){
            超级(itemView);
            名称=(TextView)itemView.findViewById(R.id.name);
            日期=(TextView)itemView.findViewById(R.id.date);
            时间=(TextView)itemView.findViewById(R.id.time);
            price =(TextView)itemView.findViewById(R.id.price);
            location =(TextView)itemView.findViewById(R.id.location);

            viewBackground = itemView.findViewById(R.id.view_background);
            viewForeground = itemView.findViewById(R.id.view_foreground);



        }}



    公共无效removeItem(int位置){
        bookings.remove(position);
        //通知按位置删除的商品
        //执行回收者视图删除动画
        //注意:请勿调用notifyDataSetChanged()
        notifyItemRemoved(position);


}


公共无效deleteItem(int位置){

    getSnapshots()。getSnapshot(position).getReference()。delete();
}

public void restoreItem(预订项,int位置){
        bookings.add(position,item);
        //通知按位置添加的项目
        notifyItemInserted(position);
    }



}
 

1 个答案:

答案 0 :(得分:0)

要从Firebase实时数据库中删除节点,您需要引用其确切的完整路径。加载数据时,您具有此类引用。例如,在onDataChange中,您可以使用以下命令删除每个节点:

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
        //Booking b = dataSnapshot1.getValue(Booking.class);
        dataSnapshot1.getRef().removeValue();
    }
}

当然不是您想要要做的,但是它显示了从Firebase删除的工作方式。您需要知道要删除的节点的完整路径,包括该子节点的密钥。

在侦听器中,您从每个子节点获取,并将其添加到列表中,然后显示在适配器中。但是您没有获得每个子节点的。这意味着您的列表/适配器仅具有删除节点所需的部分知识。到您的deleteItem函数以要删除的项目的位置被调用时,再也找不到该节点的 key 了。

因此,您需要同时跟踪适配器中的键和子节点的值。一种常见的方法是保留两个列表:一个带有键,一个带有值。

因此,首先您需要为适配器添加List<String>密钥:

ArrayList<Booking> bookings;
ArrayList<String> keys;

并在适配器的构造函数中接受它:

public MyAdapterBookings(Context c , ArrayList<Booking> b, ArrayList<String> k)
{
    context = c;
    bookings = b;
    keys = k;
}

然后将每个密钥添加到onDataChange中:

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    Log.d(TAG, "populating recyclerview");

    list = new ArrayList<Booking>();
    List<String> keys = new ArrayList<String>();
    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
        Booking b = dataSnapshot1.getValue(Booking.class);
        list.add(b);
        keys.add(dataSnapshot1.getKey());
    }
    adapter = new MyAdapterBookings(CustomerProfile.this, list, keys);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}

最后,您可以查找要删除的项目的密钥:

public void deleteItem(int position){
    String key = keys.get(position);
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Booking");
    ref.child(key).removeValue();
}