Complete the Installation and setup to connect your app to Firebase.
This will create the project in Firebase.
Add the dependency for Firebase Realtime Database to your module-level build.gradle
file:
compile 'com.google.firebase:firebase-database:9.2.1'
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!");
ThesetValue()
method overwrites data at the specified location, including any child nodes.
You can use this method to:
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);
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) {
}
});
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();
//...
}
//...
}
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
}
});
}
onDataChange()
event: @Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inflate class with dataSnapShot
Users user = dataSnapshot.getValue(Users.class);
//...
}
//User inflated
Users user = dataSnapshot.getValue(Users.class);
//Get information
this.uID = user.uID;
this.username = user.username;
this.email = user.email;
Best practices
//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
}
});
}
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