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 :
- Login to firebase console
- Select your project.
- In the left menu , select the “Database” option.
- Select the “RULES” tab.
- 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 :
1 2 3 4 |
private DatabaseReference myDatabase = FirebaseDatabase.getInstance().getReference(); myDatabase.child(node).setValue(value); |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "node1": { "node_child1": { "child1" : value_of_child1 }, "node_child2": { "child2": { "child2_child": value_of_child2 } }, } |
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:
1 2 3 4 5 6 |
private DatabaseReference myDatabase = FirebaseDatabase.getInstance().getReference(); myDatabase.child(node1).child(node_child1).child(child1).setValue(value_of_child1); myDatabase.child(node1).child(node_child2).child(child2).child(child2_child).setValue(value_of_child2); |
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 : )