How to Make a Real-Time Database with Firebase [Tutorial]

Assume you're developing an app that involves storing and sharing data from a server. You'll have to memories a lot of information, such as how to create and maintain a database.

Real-Time Database Firebase

And if you require real-time synchronization of your data or offline support, this could take a long time. Yes, using Firebase Realtime Database will save you time.

A real-time database enables you to store data and automatically sync it among users in real-time. It allows you or the other users to collaborate. Users will be able to get their own data from any device more easily as a result of this (mobile, web).

Any time you change or upload data to the Firebase servers, it will be automatically updated on the user's device in a matter of milliseconds. Isn't it incredible?

It also provides you with the option of receiving offline assistance. For example, if a user loses their data connection, the Realtime Database SDK serves the users from the device's local cache, and data is automatically synchronized once the user is back online.

Select Your Database Carefully

One thing to keep in mind for developers is that Firebase provides two types of databases,
  1. Realtime database
  2. Firestore database
So, which database should we use?

That'll be the subject of another Firebase tutorial. Don't be concerned. For you guys, I've already developed a guide. Look into: The two databases, Firebase Realtime Database and Cloud Firestore, have significant differences.

Let's get started with the tutorial now.

Step-by-Step Instructions for Creating a Firebase Realtime Database

To begin, you must either start a new Android Studio project or open an existing one.

Incorporate the Firebase Database SDK into your app.

Step 1 - To begin, go to the top toolbar and select Tools -> Firebase. After that, on the left side of Android Studio, you'll notice Firebase's assistant is open.

Step 2 - Then, by selecting the Realtime Database drop-down icon, you will be presented with a save and retrieve data option, which you should select.

Step 3 - After that, select Connect to Firebase.

Step 4 - After that, a new window will open in which you can either create a new Firebase project or pick an existing one, pick your country, and click Connect to Firebase.

Step 5 - Then, under Add the Realtime Database to Your App, select Add the Realtime Database to Your App. There is a pop-up box that appears. You can see all of the dependencies that are required to complete this project here. Simply click the Apply changes button now.

Step 6 - Now navigate to [your project name]-> app -> source and double-check that you have a google-services.json file and that your dependencies are configured correctly.

Step 7 - After that, go to the Firebase Console and look for your project. Simply open your project.

Step 8 - Then, under Realtime database, go to the database and click Create database.

Step 9 - You must choose the database rules for your project here. There are two modes to choose from.
  1. Test Mode: In this mode, anyone can view and write to your database. At the period of application development, you can follow this rule. This mode is only meant to be used for testing. You can secure your rules after you've finished the application.
  2. Locked Mode: In this mode, all reads and writes from web and mobile clients are rejected. Your authenticated application servers may still be able to access your database. Choose your mode carefully, then click Enable.

Database Security Rules Configuration

The Firebase Realtime Database includes an expressive rules language that lets you specify how data should be formatted, indexed, and when it may be published to and read from.

Write and read access to the database is restricted by default, allowing only verified (authenticated) users to write and read the data.

But don't worry, you can alter your rules to a public setting if you want to.

On database security rules, I've already written a lot.

For a thorough explanation of database security rules, see Real-time Database Security Rules.

What Is a Database and How Do I Make One?

The function get Instance () is used to retrieve the database's whole instance. Then, using that instance, save the data to the specified place, as seen in the code sample below.

//Publish a message in the database.
FirebaseDatabase database = FirebaseDatabase.getInstance();             //Retrieve the database instance and save it as an object.
DatabaseReference myRef = database.getReference("message");             //obtainReference () If the refrence has already been made, it will be returned. if the refrence has not yet been generated, it will be produced here.

myRef.setValue("Hello, World!");  
//Assign a value to a certain reference.

In the Firebase console, the Database reference looks as in the image below.

Create reference database

If you want to establish a multi-node database, use the getRefrence() method to set the path,

//Publish a message in the database.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message/java/user");      
//To get many dropdown nodes, set a path.

myRef.setValue("Hello, World!");

And the result is as seen in the image below.

Multiple nodes database

You may see the same path in the top that you supplied in the code part if you click on the user.

Multiple nodes customization

.child() can also be used to achieve the same results.

FirebaseDatabase database = FirebaseDatabase.getInstance();
//To achieve the same goals, you can use use.child().
DatabaseReference myRef = database.getReference("message").child("java").child("user");   

myRef.setValue("Hello, Worldd!");

How to Read Database

We've now entered the info into the database. It's time to get that information out of the Firebase database.

You must now attach a ValueEventListener to the object of the reference you established in the higher part to update your application data in Realtime.

When this method is tied to the listener, the onDataChange() method is called once whenever data is modified, including their children's onDataChange() methods.

//Take a look at the database
myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        //This method is called twice, the first time with the initial value and the second time with the new value.
        //everytime this location's info is updated
        String value = dataSnapshot.getValue(String.class);
        Log.d(TAG, "Value is: " + value);
    }

    @Override
    public void onCancelled(DatabaseError error) {
        //It was not possible to read the value.
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});

Put this code in your app and execute it. The output will appear in the Logcat window.

How can I remove a node from a database?

Similarly, by using the following simple code, you can delete the node. Simply get the reference path's value and set it to null, or attach removeValue() to it.

Similarly, by using the following simple code, you can delete the node. Simply get the reference path value and set it to null, or attach remove Value() to it.

When you delete a node, the Realtime database is updated immediately. When you delete a node, it turns red and is removed from the Realtime database console, as shown in the figure below.

delete node Realtime database

In the database, how to update a node

The value in the database is set with .setValue(“String”). The procedure is straightforward and similar to the other codes listed above.

You can also use the listener to determine whether or not the procedure was successful.

https://firebasetutorials.com/create-firebase-realtime-database/

//In the database, make a change to a node.
update = findViewById(R.id.update);
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) 
{
    FirebaseDatabase database1 = FirebaseDatabase.getInstance();
    DatabaseReference reference = database1.getReference().child("message").child("java").child("user");
    reference.setValue("arslan khan")
    //You can also use listenr to determine whether or not the operation was successful.
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            //It was a success to write
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            //Write failed
        }
    });
}
});

Complete Code of the Application

Here is my complete MainActivity.java code

package com.testdemo2020.loginwithgoogle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;

public class secondActivity extends AppCompatActivity 
{
    Button button2,update;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        //Publish a message in the database.
        final FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("message").child("java").child("user");

        myRef.setValue("Hello, Worldd!");

        //Take a look at the database
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                //This method is called twice, the first time with the initial value and the second time with the new value.
                //everytime this location's info is updated
                String value = dataSnapshot.getValue(String.class);
                Log.d("TAG", "Value is: " + value);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                //The value was not read.
                Log.w("TAG", "Failed to read value.", error.toException());
            }
        });

        //Remove all Node data from the database.
        button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() 
{
            @Override
            public void onClick(View v) {
                DatabaseReference dbNode = FirebaseDatabase.getInstance().getReference().getRoot().child("python").child("user");
                dbNode.setValue(null);
                //Alternatively, you may use the following code to delete the node.
                DatabaseReference dbNodetwo = FirebaseDatabase.getInstance().getReference().getRoot()
                        .child("php").child("User");
                dbNodetwo.removeValue();

            }
        });

        //In the database, make a change to a node.
        update = findViewById(R.id.update);
        update.setOnClickListener(new View.OnClickListener() 
{
            @Override
            public void onClick(View v) 
{
                FirebaseDatabase database1 = FirebaseDatabase.getInstance();
                DatabaseReference reference = database1.getReference().child("message").child("java").child("user");
                reference.setValue("arslan khan")
                //You can also use listener to determine whether or not the operation was successful.
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        //It was a success to write
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        //Write failed
                    }
                });
            }
        });
    }
}

Post a Comment

Previous Post Next Post