Open In App

How to Delete Data from Firebase Realtime Database in Android?

Last Updated : 16 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see How to Delete added data inside our Firebase Realtime Database. So we will move towards the implementation of this deleting data in Android Firebase.  

What we are going to build in this article?  

We will be showing a simple AlertBox when the user long clicks on the item of RecyclerView. It will have two options. (Delete and Cancel) .When the user clicks on delete it will simply delete that value. You can refer to How to Save Data to the Firebase Realtime Database in Android to learn how to save data in Firebase.

Note: You can use Hashmap to save data in firebase.

Further you can also directly add data in firebase like shown below

Step By Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:textSize="22sp"
        android:text="Loreum"
        android:textStyle="bold"/>
   
</LinearLayout>


Step 3: Working with the DModel.java file

Go to the DModel.java file and refer to the following code. Below is the code for the DModel.java file.  

Java




package com.anni.uploaddataexcelsheet;
 
public class DModel {
    public DModel() {
    }
 
    public String getTime() {
        return time;
    }
 
    public DModel(String time, String name) {
        this.time = time;
        this.name = name;
    }
 
    public void setTime(String time) {
        this.time = time;
    }
 
    String time;
    public DModel(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    String name;
}


Step 4: Working with the DAdapter.java file

Go to the DAdapter.java file and refer to the following code. Below is the code for the DAdapter.java file  

Java




package com.anni.uploaddataexcelsheet;
 
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
 
import com.google.firebase.auth.FirebaseAuth;
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 java.util.List;
 
public class DAdapter extends RecyclerView.Adapter {
 
    List<DModel> notifications;
 
    public DAdapter(List<DModel> notifications, Context context) {
        this.notifications = notifications;
        this.context = context;
    }
 
    Context context;
 
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_delete,parent,false);
        return new MyHolder(view);
    }
 
    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {
 
          // get the item value by positions
        String text=notifications.get(position).getName();
        final String time=notifications.get(position).getTime();
        ((MyHolder)holder).notification.setText(text);
           
          // click on item to be deleted
        ((MyHolder)holder).notification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CharSequence options[]=new CharSequence[]{
                          // select any from the value
                        "Delete",
                        "Cancel",
                };
                AlertDialog.Builder builder=new AlertDialog.Builder(holder.itemView.getContext());
                builder.setTitle("Delete Content");
                builder.setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                          // if delete option is choosed
                          // then call delete function
                        if(which==0) {
                            delete(position,time);
                        }
 
                    }
                });
                builder.show();
            }
        });
 
    }
 
    private void delete(int position, String time) {
          // creating a variable for our Database
        // Reference for Firebase.
        DatabaseReference dbref= FirebaseDatabase.getInstance().getReference().child("DataValue");
      // we are use add listerner
      // for event listener method
      // which is called with query.  
      Query query=dbref.child(time);
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                // remove the value at reference
                dataSnapshot.getRef().removeValue();
            }
 
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
 
            }
        });
    }
 
 
    @Override
    public int getItemCount() {
        return notifications.size();
    }
    class MyHolder extends RecyclerView.ViewHolder{
 
        TextView notification;
        public MyHolder(@NonNull View itemView) {
            super(itemView);
            notification=itemView.findViewById(R.id.name);
        }
    }
}


Step 6: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file  

Java




import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
import android.os.Bundle;
 
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.ValueEventListener;
 
import java.util.ArrayList;
import java.util.List;
 
public class DeleteData extends AppCompatActivity {
    List<DModel> notifications;
    DAdapter adapterNotification;
 
    RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delete_data);
           
        // Initialise layout
        recyclerView=findViewById(R.id.recyclerview);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(DeleteData.this);
           
        // reverse the layout
        linearLayoutManager.setReverseLayout(true);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(linearLayoutManager);
        notifications=new ArrayList<>();
         
         // creating a variable for our Database
        // Reference for Firebase.
        DatabaseReference reference= FirebaseDatabase.getInstance().getReference("DataValue");
     
      // we are using add value event listener method
      // which is called with database reference.
      reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                // clear the data
                notifications.clear();
                for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()) {
                    DModel modelNotification = dataSnapshot1.getValue(DModel.class);
                    notifications.add(modelNotification);
                    adapterNotification = new DAdapter(notifications,DeleteData.this);
                    // set the adapter
                    recyclerView.setAdapter(adapterNotification);
                    adapterNotification.notifyDataSetChanged();
                }
            }
 
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
 
            }
        });
    }
}


Database Structure 

Output: 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads