Friday, 2 September 2016

Firebase in Android - Adding Realtime Database

With reference from my last blog here, now we go forward towards the next step for adding Realtime database to your android app.

-Prerequisites:
- Install the Firebase in Android - Getting started.
- In the Firebase console, add your app to your Firebase project.

- Add the dependency for Firebase Realtime Database to your app-level build.gradle file:

                      compile 'com.google.firebase:firebase-database:9.4.0'

- Configure databse rules:
The Realtime database provides a declarative rules language that allows you to define how your data should be structured, how it should be indexed, and when your data can be read from and written to.By default, read and write access to your database is restricted so that only authenticated users can read or write data.You can change your permissions to your database by defining your rules.Changing your rule set from default  will make your database open to anyone, even people not using your app, so be sure to restrict your database again when you set up authentication.

- Write to your database
Create an instance of your database using getInstance() and reference the location (node) in your database where you want to write your data.

// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
myRef.setValue("Hello, World!");

You can save a range of data types to the database this way,including Java objects.When you save an object the responses from any getters will be saved as children of this location.

- Read from your database
To make your app data update in realtime i.e data from database in constant sync with your app,you should add a ValueEventListener to the reference you just created.
The onDataChange() method in this class is triggered once when the listener is attached and again every time the data changes,including the children.

// Read from the database with reference you created above
myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // This method is called once with the initial value and again
        // whenever data at this location is updated.
        String value = dataSnapshot.getValue(String.class);
        Log.d(TAG, "Value is: " + value);
    }

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

});

- Structure Your Database
Building a properly structured database requires quite a bit of forethought. Most importantly, you need to plan for how data is going to be saved and later retrieved to make that process as easy as possible.

How data is structured: it's a JSON tree
All Firebase Realtime database data is stored as JSON objects. You can think of the database as a cloud-hosted JSON tree. Unlike a SQL database, there are no tables or records. When you add data to the JSON tree, it becomes a node in the existing JSON structure with an associated key. You can provide your own keys, such as user IDs or semantic names, or they can be provided for you using push().
For example, data in your database may look like as follows when you are storing some user details:


     "users": {
          "userid_node_for_creating_user": {
                                       "userEmailAddress":"xx@yyy.zz", 
                                       "userFirstName":"First Name",
                                       "userGender":"Male",
                                       "userLastName":"Last Name",
                                       "userMobileNumber":"0099990099",
                                       "userName":"User_1"
                          }
               }
  }

Although the database uses a JSON tree, data stored in the database can be represented as certain native types that correspond to available JSON types to help you write more maintainable code.

- Best practices for data structure

- Avoid nesting data:
Although the Firebase Realtime database allows nesting of data up to 32 levels deep, you might think that this should be the default structure. However, when you fetch data at a location in your database, you also retrieve all of its child nodes. Also, when you grant someone read or write access at a node in your database, you also grant them access to all data under that node. Therefore, in practice, it's best to keep your data structure as flat as possible.
- Use Flatten data structures:
If the data is instead split into separate paths, it can be efficiently downloaded in separate calls, as it is needed.

That's all for now. We will proceed further in next page. Till then try this much first.

No comments:

Post a Comment