firebase-database FirebaseRealtime database with Android Example for data insert or data retrieve from Firebase

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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) {
    
              }
          });
    


Got any firebase-database Question?