Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Save Data to the Firebase Realtime Database in Android?
Next article icon

How to Delete Data from Firebase Realtime Database in Android?

Last Updated : 16 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
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      xmlns:android="http://schemas.android.com/apk/res/android"     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: 


 


Next Article
How to Save Data to the Firebase Realtime Database in Android?

A

annianni
Improve
Article Tags :
  • Java
  • Android
  • Firebase
Practice Tags :
  • Java

Similar Reads

  • How to Retrieve Data from the Firebase Realtime Database in Android?
    Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous is for its Firebase Realt
    5 min read
  • How to Retrieve Data from Firebase Realtime Database in Android ListView?
    Firebase Realtime Database provides us a feature to give Real-time updates to your data inside your app within milli-seconds. With the help of Firebase, you can provide Real-time updates to your users. In this article, we will take a look at the implementation of the Firebase Realtime Database for o
    7 min read
  • How to Delete Data in Realm Database in Android?
    In the previous series of articles on the realm database, we have seen adding, reading, and updating data using the realm database in android. In that articles, we were adding course details, reading them, and updating them. In this article, we will take a look at deleting these course details from
    6 min read
  • How to Retrieve PDF File From Firebase Realtime Database in Android?
    When we are creating an Android app then instead of inserting a pdf manually we want to fetch the pdf using the internet from Firebase. Firebase Realtime Database is the backend service that is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It
    8 min read
  • How to Save Data to the Firebase Realtime Database in Android?
    Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simp
    7 min read
  • How to Read Data from SQLite Database in Android?
    In the 1st part of our SQLite database, we have seen How to Create and Add Data to SQLite Database in Android. In that article, we have added data to our SQLite Database. In this article, we will read all this data from the SQLite database and display this data in RecyclerView. What we are going to
    12 min read
  • How to Upload Excel/Google Sheet Data to Firebase Realtime Database in Android?
    Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous for its Firebase Realtime
    11 min read
  • How to Read Data from Realm Database in Android?
    In the previous article, we have seen adding data to the realm database in Android. In this article, we will take a look at reading this data from our Realm Database in the Android app.  What we are going to build in this article?  In this article, we will be simply adding a Button to open a new act
    8 min read
  • How to Delete Data in SQLite Database in Android?
    In the previous articles, we have seen three operations of CRUD operations such as create, read and update operations in our Android app. In this article, we will take a look at adding delete operation for deleting our items stored in the SQLite database.  What we are going to build in this article?
    8 min read
  • How to Read Data from Firebase Firestore in Android?
    In the previous article, we have seen on How to Add Data to Firebase Firestore in Android. This is the continuation of this series. Now we will see How to Read this added data inside our Firebase Firestore. Now we will move towards the implementation of this reading data in Android Firebase.  What w
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences