Writing data to your firebase realtime database

Writing data to your firebase realtime database

In last blog , we discussed how to add firebase realtime database in your android project.

Now , we will look into how you can read and write to the same.

For this first you need to understand that this database is a NOSQL database.

With this statement what i actually mean to imply is that this databse reads and writes data in the form of JSON Objects and JSON arrays. (Nothing like SELECT * FROM ‘X’  WHERE A==B) .

Now, coming to the main point, this databases provides you a json array where in you can simply access all the objects.

Before we start with the actual methods, you would first like to change the permissions of the database on the firebase console so that you might be able to read and write to the database provided.
For this, all you need to do is :

  1. Login to firebase console
  2. Select your project.
  3. In the left menu , select the “Database” option.
  4. Select the “RULES”  tab.
  5. Now change the permission as per your requirement.

For more details on how exactly to do it, please refer here .

Now back to our main topic,

To write data , all you need to do is get the reference to your database and then select the proper child node and then the child key (as per your structure )where you want to add the value and after this all you need to do is call the setValue(String value) to write the data to that particular key.


Code Snippet :

This was just on how to  add value to the node that is the child of your root node, but this case never happens in the real world.

In real world we have objects with somewhat structure like:

OR a much complex json structure where in this child has many levels :

In order to write exactly to the attribute  which you want to , you can do like this:

OR , you can make a POJO model, add data to one of the instances of object and add whole model to a single node just like in the first case.

Thats all on how exactly to write data on your firebase realtime database.

In new blog we will learn on how to read data from firebase database.

For seeing last blog, click here

Thanks !

Keep coding and keep sharing : )