Open In App

Firebase RealTime Database with Operations in Android with Examples

Firebase Realtime Database is a Cloud hosted database, i.e. it runs on a cloud and access to the user is provided as a service. It stores data in JSON (Javascript Object Notation) format, a format to store or transport data. All the users connected to it can get access to the data at Real Time.



Features of Firebase Realtime Database?



  1. Real Time: Due to the Data synchronization used in Real Time, every update is received by the devices/clients in no time.
  2. No need of Application Server: As the database can be accessed directly from the mobile device or browser there is no need for an Application Server.
  3. Support by various languages and platforms:

  4. Splitting Data: The client can split the data across multiple database instances for the same project.
  5. Client-Side Code: The dynamic applications with the secured data can be accessed directly from the client-side code.
  6. Cross-Platform: It can be used for building a back-end for various platforms like Android, iOS, Web, iOS as well as JavaScript SDK.

Structuring the Realtime Database:

Firebase Realtime Database stores data as one large JSON tree. It stores simple data easily, but the unstructured hierarchical data is difficult to organize. Unlike SQL there are no tables here.

Writing/Inserting data into Firebase Realtime Database

Writing the data to the Firebase is a very easy task. But before writing / inserting the data to the Realtime database the Structuring of the data should be done. Inserting or writing the data to the Firebase Realtime database is done in Android using the function setValue(). Inserting the data to the Firebase Realtime database can be considered as one of the CRUD operations.

setValue(): This function is used to:

The value/types that can be passed to it are:

Steps for Writing/Inserting data into Firebase Realtime Database:
Consider that we have to store the name of the user to the database

  1. Create a Database Reference:
    // Consider that we have to store
    // this in the database
    
    String name = "GfG1" ;
    
  2. Find the reference of the data where the value is to be stored using the child() function:
    // Create an object of Firebase Database Reference
    
    DatabaseReference reference;
    reference = FirebaseDatabase.getInstance().getReference();  
    
  3. Use the referenced object and setValue() function with the value to be stored as an argument to it in order to write the data:
    //Inserts the data to the database
    
    reference.child("user").setValue(name); 
    
  4. Output:

Example 2: Let us consider another example to store the user-defined object to the database


Article Tags :