当在回收器视图中滑动时,我试图从Firebase中删除arow。我已经设法从回收器视图中删除了记录,但正在努力从Firebase中删除它。以下是我当前使用的,在deleteItem()方法中的adpater中出现错误(在getSnapshot()方法上(无法解析方法'getSnapshot()')。
我在回收器视图的Item touch助手中的活动:
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
中,您可以使用以下命令删除每个节点:
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
//Booking b = dataSnapshot1.getValue(Booking.class);
dataSnapshot1.getRef().removeValue();
}
}
当然,这不是您想要做的,但它显示了从Firebase中删除的工作原理。您需要知道要删除的节点的完整路径,其中包括该子节点的密钥。
在您的侦听器中,您从每个子节点获取值并将其添加到列表中,然后在适配器中显示。但是您没有获得每个子节点的键。这意味着您的列表/适配器只有删除节点所需的部分知识。当您的deleteItem
函数被调用时,将无法再查找该节点的键。
因此,您需要跟踪适配器中子节点的键和值。一种常见的方法是保留两个列表:一个包含键,一个包含值。
所以首先你添加一个列表
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();
}