Before understand require to follow some setup for project integrate with firebase.
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
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) {
}
});