Firebase Real-Time Database with Android
Integrate Firebase Real-Time database with an Android application
How to implement Firebase Real-Time database in Android applications.
Setup/Installation:
-
First, install the Firebase SDK (guide)
-
Register your project using the Firebase console
-
After successfuly completing the two steps above, add the following dependency in your application level gradel.
compile 'com.google.firebase:firebase-database:9.2.1'
-
[Optional] Configure your database security rules (reference).
Implementation Sample:
-
Declare and initialize the database reference
FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message");
You can later create different references to access different nodes
-
Write new data to the database
myRef.setValue("Writing Demo");
-
Read data from the database
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()); } });