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.

  • What is JSON Tree Model?
    JSON Tree Model is inspired from JSON( JavaScript Object Notation) used to represent the JSON document which generally consists of key-value pair in memory .
  • Why to structure the data (What are the advantages of doing it)?
    • If data is stored in well formatted structure then it is easy to save as well as retrieve it easily.
    • Querying becomes easy on the structured data.
    • It becomes feasible to refer the data in structured format.
  • Key points to remember while structuring the data:

    Before writing and reading the data into the database, the main aim of the developer should be constructing the structure of the database.

    1. Consider the Nesting Limit:
      The Nesting of the data should be done in a proper way such that it should be easy to read it using Listeners(Listeners are used to reading the data from the database). Avoid unnecessary nesting of levels in the database. Firebase also allows only 32 levels of Nesting.

      For Example:

      // JSON Format Structuring Simple Example
      {
      "userinfo":
       {
        "a":
         {
          "name": "GfG1",
          "address":"GeeksForGeeksOne",
          "order_details":
          {
             "p1":
                 {
                  "product_id":"1",
                  "quantity":"5",
                  "price":"500",
                  "address_of_delivery":"xyz, abc, ..."
                 },
              
             "p2":
                 {
                  "product_id":"2",
                  "quantity":"10",
                  "price":"1000",
                  "address_of_delivery":"xyz2, abc, ..."
                 }
      
          }
        },
      
        "b":
         {
          "name": "GfG2",
          "address":"GeeksForGeeksTwo",
          "order_details":
          {
             "p1":
                 {
                  "product_id":"1",
                  "quantity":"12",
                  "price":"1500",
                  "address_of_delivery":"pqr, abc, ..."
                 },
              
             "p2":
                 {
                  "product_id":"2",
                  "quantity":"18",
                  "price":"1000",
                  "address_of_delivery":"pqr2, abc, ..."
                 }
      
          }
        }
        }
      }
      
      

      In this example, retrieving the data of names of users is very difficult as we have to access the child nodes of users_info which downloads the data having several MB’s sizes (in this case name, orders_details, address, etc gets downloaded).

    2. Design a Denormalized form of Data:
      The Flattening of the data should be done correctly, means that data should be split into different parts without any ambiguity. This is generally referred to as denormalisation, where in order to improve read performance we develop redundancy in the data.


      For Example:

      // JSON Format Example with Denormalized form for example in Point 1
      {
       "user_info":
          {
            "a":    
               {
              "name": "GfG1",
              "address":"GeeksForGeeksOne"    
               },
      
             "b":
               {
              "name": "GfG2",
              "address":"GeeksForGeeksTwo"
               }    
          },
       "order_details":
          {
           "a":
              {
               "p1":
                {
                  "product_id":"1",
                  "quantity":"5",
                  "price":"500",
                  "address_of_delivery":"xyz, abc, ..."
                 },    
                  
                  "p2":
               {
                  "product_id":"2",
                  "quantity":"10",
                  "price":"1000",
                  "address_of_delivery":"xyz2, abc, ..."
               }    
              },
          "b":
             {
             "p1":
                 {
                  "product_id":"1",
                  "quantity":"12",
                  "price":"1500",
                  "address_of_delivery":"pqr, abc, ..."
                 },
              
             "p2":
                 {
                  "product_id":"2",
                  "quantity":"18",
                  "price":"1000",
                  "address_of_delivery":"pqr2, abc, ..."
                 }    
      
             }    
          }
      
      
      }
      
      

      In this example, the data is split as user_info and order_deatils. Due to this, the accessibility of the data is faster and hence, no need to download the oversized unnecessary data. Here, Retrieving the data of names of users is very simple as we have to access the child nodes of users_info which downloads the data having a name and address details only and no details of orders are processed.

    3. Create a structure which is Dynamic in Nature:
      The structuring of the data should be such that it should be scalable. Sometimes in order to have easy accessibility of the data, duplication needs to be implemented in the database.

      For Example:

      // JSON Format Example explaining the Scaling property
      {
       "student_info":
         {
          "1":
          {
            "name":"GfG1",
             "roll_no":"1",
             "exam_board":"abc"    
          },
      
          "2":
          {
            "name":"GfG2",
             "roll_no":"2",
             "exam_board":"pqr"    
          },
          
          "3":
          {
             "name":"GfG3",
             "roll_no":"3",
             "exam_board":"abc"    
          }
         },
       
       "board_info":
         {
          "abc":
               {    
              "student_names":
                     {
                    "GfG1":true,
                    "GfG2":false,
                    "GfG3":true    
                     }    
               },
          
          "pqr":
               {    
              "student_names":
                     {
                    "GfG1":false,
                    "GfG2":true,
                    "GfG3":false    
                     }    
               }
         }
      
      }
      
      

      In the above example, in order to access the database easily, the name of the board is stored in every students information as well as the board information stores the name of the student and the board he is having. If we had not stored the data under board information, then it would be difficult to collect the names of students having a particular board.

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:

  • Replace the data at the referenced position
  • If no data present at the referenced position then it writes the data directly at that position

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

  • STEP 1:
    // Create a class User
    
    class User
    {
        String name;
        String address;
    
         User()
         {
             name = "";
             address = "";
         }
        
         User(String name, String address)
         {
            this.name = name;
            this.address = address;
         }
    
    } 
    
  • STEP 2:
    // Create a user-defined object
    
    User user1 = new User("GfG1", "GeeksForGeeks");
    
  • STEP 3:
    // Create an object of Firebase Database Reference
    
    DatabaseReference reference ;
    reference = FirebaseDatabase.getInstance().getReference();  
    
    // Insert the user-defined object to the database 
    
    reference.child("user").setValue(user1); 
    
  • Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.