/firebase-tutorials

How to delete data in Realtime Database?

Learn to delete data in Firebase Realtime Database across Web, Android, and iOS with our step-by-step guide to set up, access, and remove node data safely.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to delete data in Realtime Database?

 

Step 1: Set Up Firebase Project

 

First, you need to set up a Firebase project if you haven't already:

  1. Go to the Firebase Console.
  2. Click on "Add Project".
  3. Follow the instructions to create a new project.

 

Step 2: Set Up Realtime Database

 

After setting up the Firebase project, you need to enable the Realtime Database:

  1. In your Firebase project console, navigate to the "Realtime Database" section.
  2. Click on "Create Database".
  3. Choose the security rules according to your needs (for testing, you might want to set up public rules, but for production, ensure secure rules).

 

Step 3: Add Firebase SDK to Your Project

 

Next, integrate Firebase SDK into your app. Here's how to do it for different environments:

Web Application:

Add Firebase to your HTML file:

<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js"></script>

<script>
  // Your web app's Firebase configuration
  const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "your-app.firebaseapp.com",
    databaseURL: "https://your-app.firebaseio.com",
    projectId: "your-app",
    storageBucket: "your-app.appspot.com",
    messagingSenderId: "SENDER_ID",
    appId: "APP_ID"
  };

  // Initialize Firebase
  const app = firebase.initializeApp(firebaseConfig);
  const database = firebase.database(app);
</script>

Android Application:

In your build.gradle (Project level), ensure that you have the Google services classpath:

buildscript {
  dependencies {
    ...
    classpath 'com.google.gms:google-services:4.3.10'
  }
}

In your build.gradle (app level), add the Firebase Database dependency and apply the Google services plugin:

plugins {
  ...
  id 'com.android.application'
  id 'com.google.gms.google-services'
}

dependencies {
  ...
  implementation 'com.google.firebase:firebase-database:20.0.3'
}

iOS Application:

In your Podfile add Firebase/Database pod:

pod 'Firebase/Database'

Run pod install to install the Firebase SDK.

 

Step 4: Access Database Reference

 

First, you'll need a reference to your Firebase Realtime Database.

JavaScript:

const dbRef = firebase.database().ref();

Java (Android):

DatabaseReference database = FirebaseDatabase.getInstance().getReference();

Swift (iOS):

let ref: DatabaseReference! = Database.database().reference()

 

Step 5: Delete Data from Realtime Database

 

To delete data from a Realtime Database, you have multiple options. You can delete a specific node, or if you want to delete the entire database, you can specify the root node.

JavaScript (Web):

To delete a specific node:

const nodeRef = dbRef.child('path/to/node');
nodeRef.remove()
  .then(() => {
    console.log("Remove succeeded.")
  })
  .catch((error) => {
    console.log("Remove failed: " + error.message)
  });

Java (Android):

To delete a specific node:

DatabaseReference nodeRef = database.child("path/to/node");
nodeRef.removeValue()
  .addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        // Successfully deleted
    }
  })
  .addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception databaseError) {
        // Failed to delete
    }
  });

Swift (iOS):

To delete a specific node:

let nodeRef = ref.child("path/to/node")
nodeRef.removeValue { error, _ in
    if let error = error {
        print("Remove failed: \(error.localizedDescription)")
    } else {
        print("Remove succeeded.")
    }
}

 

Step 6: Confirm Data Deletion

 

To ensure that the data has been successfully deleted, you can read the data from the database and confirm. This step can be optional if you're confident that the remove operation succeeded.

JavaScript:

nodeRef.once('value')
  .then((snapshot) => {
    if (snapshot.exists()) {
      console.log("Data still exists.");
    } else {
      console.log("Data deleted successfully.");
    }
  });

Java (Android):

nodeRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            // Data still exists
        } else {
            // Data deleted successfully
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Read failed
    }
});

Swift (iOS):

nodeRef.observeSingleEvent(of: .value, with: { snapshot in
    if snapshot.exists() {
        print("Data still exists.")
    } else {
        print("Data deleted successfully.")
    }
})

With these steps, you have learned how to delete data in Firebase Realtime Database using different programming languages. Be sure to handle exceptions and errors as shown to ensure a robust application.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022