FirebaseRealtime database with Android

Other topics

Add the Realtime Database in Android

  1. Complete the Installation and setup to connect your app to Firebase.
    This will create the project in Firebase.

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

compile 'com.google.firebase:firebase-database:9.2.1'
  1. Configure Firebase Database Rules

Now you are ready to work with the Realtime Database in Android.

For example you write a Hello World message to the database under the message key.

// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");

myRef.setValue("Hello, World!");

Using setValue to save data

ThesetValue() method overwrites data at the specified location, including any child nodes.

You can use this method to:

  1. Pass types that correspond to the available JSON types as follows:
  • String
  • Long
  • Double
  • Boolean
  • Map<String, Object>
  • List
  1. Pass a custom Java object, if the class that defines it has a default constructor that takes no arguments and has public getters for the properties to be assigned.

This is an example with a CustomObject.
First define the object.

@IgnoreExtraProperties
public class User {

    public String username;
    public String email;

    public User() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public User(String username, String email) {
        this.username = username;
        this.email = email;
    }

Then get the Database reference and set the value:

   User user = new User(name, email);
   DatabaseReference mDatabase mDatabase = FirebaseDatabase.getInstance().getReference();
   mDatabase.child("users").child(userId).setValue(user);

Example for data insert or data retrieve from Firebase

Before understand require to follow some setup for project integrate with firebase.

  1. Create your project in Firebase Console and download google-service.json file from console and put it in app level module of your project, Follow link for Create Project in console

  2. After this we require to add some dependency in our project,

  • First add class path in our project level gradle,

    classpath 'com.google.gms:google-services:3.0.0'

  • And after that apply plugin in app level gradel,write it below of dependancy section,

    apply plugin: 'com.google.gms.google-services

  • There are to more dependancy which require to add in app level gradle in dependancy section

    compile 'com.google.firebase:firebase-core:9.0.2'

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

  • Now start to insert data in firebase database, First require to create instance of

    FirebaseDatabase database = FirebaseDatabase.getInstance();

    after creation of FirebaseDatabase object we going to create our DatabaseReference for insert data in database,

    DatabaseReference databaseReference = database.getReference().child("student");

    Here student is the table name if table is exist in database then insert data into table otherwise create new one with student name, after this you can insert data using databaseReference.setValue(); function like following,

    HashMap<String,String> student=new HashMap<>();

    student.put("RollNo","1");

    student.put("Name","Jayesh");

    databaseReference.setValue(student);

    Here I am inserting data as hasmap But you can set as model class also,

  • Start how to retrieve data from firebase, We are using here addListenerForSingleValueEvent for read value from database,

      senderRefrence.addListenerForSingleValueEvent(new ValueEventListener() {
              @Override
              public void onDataChange(DataSnapshot dataSnapshot) {
                  if(dataSnapshot!=null && dataSnapshot.exists()){
                      HashMap<String,String> studentData=dataSnapshot.getValue(HashMap.class);
                      Log.d("Student Roll Num "," : "+studentData.get("RollNo"));
                      Log.d("Student Name "," : "+studentData.get("Name"));
                  }
              }
    
              @Override
              public void onCancelled(DatabaseError databaseError) {
    
              }
          });
    

Get value/s from firebase

  1. Create class and add imports to parse information:
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.IgnoreExtraProperties;

//Declaration of firebase references
private DatabaseReference mDatabase;

//Declaration of firebase atributtes
public String uID;
public String username;
public String email;

@IgnoreExtraProperties
public class User {

    //Default constructor
    public User() {

        //Default constructor required for calls to DataSnapshot.getValue(User.class)
        mDatabase = FirebaseDatabase.getInstance().getReference();

        //...
    }

    //...
}
  1. Add addListenerForSingleValueEvent() to our database reference:
//Add new imports
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;

//...

public void getUser(String uID){

    //The uID it's unique id generated by firebase database
    mDatabase.child("users").child(uID).addListenerForSingleValueEvent(
            new ValueEventListener () {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // ...
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
            }
    });
}
  1. Inflate our class with firebase information in onDataChange() event:
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //Inflate class with dataSnapShot
            Users user = dataSnapshot.getValue(Users.class);

            //...
        }
  1. Finally we can get diferent atributtes from firebase class as normally:
//User inflated
Users user = dataSnapshot.getValue(Users.class);

//Get information
this.uID = user.uID;
this.username = user.username;
this.email = user.email;

Best practices

  1. The firebase supports 32 different child levels, then is simple to write wrong a references, to evade this create a final private references:
//Declaration of firebase references
//...
final private DatabaseReference userRef = mDatabase.child("users").child("premium").child("normal").getRef();

//...

public void getUser(String uID){

    //Call our reference
    userRef.child(uID).addListenerForSingleValueEvent(
        new ValueEventListener () {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // ...
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
            }
    });
}
  1. The onCancelled() event is called when the user doesn't have access this reference by database rules. Add pertinent code to control this exception if you need.

For more information visit official documentation

Contributors

Topic Id: 6220

Example Ids: 21526,21527,22118,22426

This site is not affiliated with any of the contributors.