简体   繁体   中英

Delete a node from Firebase realtime database with android studio java Recycler view

How can I get the child id which is inserted using push().getKey() while inserting data into the database for applying a delete method for node? I have used recyclerView to show data as cards.

Here is my Firebase DB:

Prescription
   -MkWDI1v55zkQDdiGa8T
   -MkXdxxXLoJgFJVQYDpo
      -LP6RF0KD7Ve66snlayZjpSotQEJ2   //This is a unique ID that is provided by firebase authentication
         -Ml-I9XVcNnOM8nc79sw         //This is the Ordered Item 1
             name: "Atarax"
             qty: "30"
             total: "300.00"
             unitPrice: "10.00"
         -Ml-M1pN4zsyyRf7pHeM         //This is the Ordered Item 2
             name: "Vitamin C"
             qty: "10"
             total: "500.00"
             unitPrice: "50.00"

Here is my Adapter class:

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

    SpinKitView pbDelete;
    Context context;
    ArrayList<Orders> list;
    DatabaseReference reference;


    public Cart_adapter(Context context, ArrayList<Orders> list, SpinKitView pbDelete) {
        this.context = context;
        this.list = list;
        this.pbDelete = pbDelete;
    }

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

    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
        Orders order = list.get(position);
        holder.iname.setText(order.getName());
        holder.qty.setText(order.getQty());
        holder.unitPrice.setText(order.getUnitPrice());
        holder.totPrice.setText(order.getTotal());




        //Delete from Firebase Database
        holder.btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                pbDelete.setVisibility(View.VISIBLE);

                String key = FirebaseAuth.getInstance().getCurrentUser().getUid().toString();
                
                reference = FirebaseDatabase.getInstance().getReference("Prescription").child(key);
                
                FirebaseDatabase.getInstance().getReference("Prescription").child(key)
                        .child(reference.getKey().toString()).removeValue();
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder{

        TextView iname, qty, unitPrice, totPrice;
        Button btn_delete;
        LinearLayout orderCard;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            iname = itemView.findViewById(R.id.tv_itemName);
            qty = itemView.findViewById(R.id.tv_qty);
            unitPrice = itemView.findViewById(R.id.tv_unitPrice);
            totPrice = itemView.findViewById(R.id.tv_totalPrice);
            btn_delete = itemView.findViewById(R.id.btn_remove);
            orderCard = itemView.findViewById(R.id.layout_order);
        }
    }

Here is my Orders class:

package com.edu.wellwork;

public class Orders{

    public String name;
    public String qty;
    public String unitPrice;
    public String total;

    public Orders() {
    }

    public Orders(String name, String qty, String unitPrice, String total) {
        this.name = name;
        this.qty = qty;
        this.unitPrice = unitPrice;
        this.total = total;
    }

    public Orders(String itemName, String qty) {
        this.name = itemName;
        this.qty = qty;
    }

    public String getName() {
        return name;
    }

    public String getQty() {
        return qty;
    }

    public String getUnitPrice() {
        return unitPrice;
    }

    public String getTotal() {
        return total;
    }
}

How do I get the unique key (which is the parent node of each order) to delete an ordered item from the database?

According to your comment:

I can navigate until to the node that provided by firebase authentication (LP6RF0KD7Ve66snlayZjpSotQEJ2) using this: DatabaseReference db =FirebaseDatabase.getInstance().getReference("Prescription").child(authCode); db.removeValue() But this will delete the entire user's nodes

Indeed you are removing the entire node since your reference points exactly to that node. To be able to remove the -Ml-I9XVcNnOM8nc79sw node, you should create a reference that points exactly to that node:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference nodeToRemove = rootRef
    .child("Prescription")
    .child("-MkXdxxXLoJgFJVQYDpo")
    .child("-LP6RF0KD7Ve66snlayZjpSotQEJ2")
    .child("-Ml-I9XVcNnOM8nc79sw");
nodeToRemove.removeValue();

Always remember that in order to remove a specific element, you need to create a reference that contains the name of all nodes, including the one that you want to delete.

If you don't have one of the keys, then you should store the value in a variable as explained in my answer from the following post:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM