从回收站视图和 firebase 中删除行 [英] Deleting row from recycler view and firebase

查看:16
本文介绍了从回收站视图和 firebase 中删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回收器视图中滑动时,我试图从 firebase 中删除 arow.我已设法从回收站视图中删除记录,但正在努力将其从 firebase 中删除.以下是我目前正在使用的,deleteItem() 方法(在 getSnapshots() 方法上(无法解析方法 'getSnapshots()')的适配器中有错误.

I am trying to delete arow from firebase when swiped in the recycler view. I have managed to remove the record from the recycler view but am struggling with deleting it from firebase. The following is what I am currently using, with an error in the adpater in the deleteItem() method (on the getSnapshots() method (Cannot resolve method 'getSnapshots()').

我的活动与回收者视图的项目触摸助手:

My activity with the Item touch helper for the recycler view:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_profile);
 Log.d(TAG, "finding recyclerview");
        recyclerView = (RecyclerView) findViewById(R.id.myRecyclerBooking);
        recyclerView.setLayoutManager( new LinearLayoutManager(this));


        Log.d(TAG, "getting db reference");



        //FirebaseSearch https://www.youtube.com/watch?v=b_tz8kbFUsU
        reference = FirebaseDatabase.getInstance().getReference().child("Booking");
        Query firebaseSearchQuery = reference.orderByChild("customerID").equalTo(mAuth.getCurrentUser().getUid());

        firebaseSearchQuery.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Log.d(TAG, "populating recyclerview");

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


            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(CustomerProfile.this, "Opsss.... Something is wrong", Toast.LENGTH_SHORT).show();
            }
        });
}

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



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

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                // Row is swiped from recycler view
                // remove it from adapter
            }

            @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);
            }
        };

        // attaching the touch helper to recycler view
        new ItemTouchHelper(itemTouchHelperCallback1).attachToRecyclerView(recyclerView);
    }

@Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {

        if (viewHolder instanceof MyAdapterBookings.MyViewHolder) {
            // get the removed item name to display it in snack bar
            String name = list.get(viewHolder.getAdapterPosition()).getMuaName();

            // backup of removed item for undo purpose
            final Booking deletedItem = list.get(viewHolder.getAdapterPosition());
            final int deletedIndex = viewHolder.getAdapterPosition();

            // remove the item from recycler view
            adapter.removeItem(viewHolder.getAdapterPosition());
            adapter.deleteItem(viewHolder.getAdapterPosition());


            // showing snack bar with Undo option
            Snackbar snackbar = Snackbar
                    .make(coordinatorLayout, "Appointment with " + name + " cancelled!", Snackbar.LENGTH_LONG);
            snackbar.setAction("UNDO", new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // undo is selected, restore the deleted item
                    adapter.restoreItem(deletedItem, deletedIndex);
                }
            });
            snackbar.setActionTextColor(Color.YELLOW);
            snackbar.show();
        }

    }

我的适配器:

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

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

import java.util.ArrayList;

public class MyAdapterBookings extends RecyclerView.Adapter<MyAdapterBookings.MyViewHolder> {

    Context context;
    ArrayList<Booking> bookings;
    DatabaseReference reference;
    private static final String TAG = "Bookings Adapter";
    public MyAdapterBookings(Context c , ArrayList<Booking> b)
    {
        context = c;
        bookings = b;
    }

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

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        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() {
        return bookings.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder
    {
        TextView name,date,time,price,location;
        public RelativeLayout viewBackground, viewForeground;
        public MyViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.name);
            date = (TextView) itemView.findViewById(R.id.date);
            time = (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);



        }    }



    public void removeItem(int position) {
        bookings.remove(position);
        // notify the item removed by position
        // to perform recycler view delete animations
        // NOTE: don't call notifyDataSetChanged()
        notifyItemRemoved(position);


}


public void deleteItem(int position){

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

public void restoreItem(Booking item, int position) {
        bookings.add(position, item);
        // notify item added by position
        notifyItemInserted(position);
    }



}

推荐答案

要从 Firebase 实时数据库中删除节点,您需要引用其准确、完整的路径.当你加载数据时,你有这样的引用.例如在 onDataChange可以删除每个节点:

To delete a node from the Firebase Realtime Database you need to have a reference to its exact, complete path. You have such references when you're loading the data. For example in the onDataChange you could delete each node with:

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

当然,这不是您想要做的,但它显示了从 Firebase 中删除是如何工作的.您需要知道要删除的节点的完整路径,包括该子节点的键.

Of course that is not what you want to do, but it shows how deleting from Firebase works. You need to know the full path of the node you're trying to delete, which including the key of that child node.

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

In your listener you get the value from each child node and add that to a list, that you then display in the adapter. But you're not getting the key of each child node. This means that your list/adapter only have part of the knowledge needed to delete the nodes. By the time your deleteItem function gets called with the position of the item to delete, there is no way to look up the key of that node anymore.

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

So you need to keep track of both the keys and the values of the child nodes that are in your adapter. A common way to do this is by keeping two lists: one with the keys, and one with the values.

因此,首先为适配器添加一个List:

So first you add a List<String> for the keys to your adapter:

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

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

And accept that in the adapter's constructor:

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

然后在 onDataChange 中添加每个键:

Then you add each key in 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();
}

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

And finally you can then look up the key for the item to delete:

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

这篇关于从回收站视图和 firebase 中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆