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

问题描述

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

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()').

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

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<String>作为密钥添加到适配器:

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:

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中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 22:50