Firebase RealTime Database

Firebase RealTime Database

step 1

Create a Database

  1. Navigate to the Realtime Database section of the Firebase console. You'll be prompted to select an existing Firebase project. Follow the database creation workflow.
FireBase Implementation
FireBase Implementation
  1. Select a starting mode for your Firebase Security Rules:
  1. Choose a location for the database.
  1. Click Done.
 

In Android Studio

step 2

  • add dependency
// Add the dependency for the Realtime Database library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-database")
 

Write to your database

Retrieve an instance of your database using getInstance() and reference the location you want to write to.
private lateinit var database: FirebaseDatabase // demo / test database = Firebase.database val myRef = database.getReference("<path>") // this change value at this path // and create data and path if not exists there myRef.setValue("Hello, World!")

Write data

Basic write operations

  • For basic write operations, you can use setValue() to save data to a specified reference.
  • can use this method to Pass types that correspond to the available JSON types as follows:
  • String
  • Boolean
  • Map<String, Object>
  • Pass a custom data class object
  • Long
  • Double
  • List<Object>
@IgnoreExtraProperties data class User( val userKey: String? = null, val username: String? = null, val number: String? = null, val imgUrl: String ) { // Default Constructor constructor() : this("", "", "", "") }
setValue() :
  • using seValue() overwrites data at the specified location, in this way including any child nodes.
Push() :
  • Create a reference to an auto-generated child location.
  • push() must be define while defining database reference path or before setValue() called
  • The child key is generated client-side and incorporates an estimate of the server's time for sorting purposes.
  • Locations generated on a single client will be sorted in the order that they are created, and will be sorted approximately in order across all clients.

Add Event after Complete Writing To Database

val myRef = database.child("users").child(userId) myRef.setValue(name).addOnCompleteListener { task -> if(task.isSuccessful){ Toast.makeText(this@AddQuoteActivity,"Quote Added",Toast.LENGTH_SHORT).show() // .... } else { Toast.makeText(this@AddQuoteActivity,"Error Occurred",Toast.LENGTH_SHORT).show() } }
 

Example

val name = "H.p Shiyani" val num = "9595004049" // write to database val database = Firebase.database // path to store data object val childPath = "Creative/katargam" val myRef = database.getReference(childPath).push() // add object / list<Object> in Object to create JSON type structure var k = kk("haresh", "mayur") val mydata = Mydata(myRef.key , name, num, imageurl , k); // this function will be used to write in database myRef.setValue(mydata) // you can also add event on complete here

Read Data From Firebase

→ Get Data as List of Object

// class / Activity member private lateinit var databaseReference: DatabaseReference // intialize database reference databaseReference = Firebase.database.reference // provide path to get data list from val quoteReference = databaseReference.child("quotes") // instantiate Value Event Listener // it will provide snapShot of Data quoteReference.addValueEventListener(object : ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot) { val quoteList = mutableListOf<Quote>() // Iterate over each data item from snapShot for (quoteSnapshot in snapshot.children){ // create data object by converting into data class object val quote = quoteSnapshot.getValue(Quote::class.java) quote?.let { // if not null than add to list quoteList.add(quote) } } val qAdapter = QuoteAdapter(quoteList) binding.mainRecyclerview.adapter = qAdapter } override fun onCancelled(error: DatabaseError) { TODO("Not yet implemented") } })
  • The listener receives a DataSnapshot that contains the data at the specified location in the database at the time of the event.
  • Calling getValue() on a snapshot returns the Java object representation of the data. If no data exists at the location, calling getValue() returns null.
  • In this example, ValueEventListener also defines the onCancelled() method that is called if the read is canceled.
  • For example, a read can be canceled if the client doesn't have permission to read from a Firebase database location.
  • This method is passed a DatabaseError object indicating why the failure occurred.
 

Read data once

 

Read once using get()

The SDK is designed to manage interactions with database servers whether your app is online or offline.
  • Generally, you should use the ValueEventListener techniques described above to read data to get notified of updates to the data from the backend.
  • The listener techniques reduce your usage and billing, and are optimized to give your users the best experience as they go online and offline.
  • If you need the data only once, you can use get() to get a snapshot of the data from the database.
  • If for any reason get() is unable to return the server value, the client will probe the local storage cache and return an error if the value is still not found.
  • Unnecessary use of get() can increase use of bandwidth and lead to loss of performance, which can be prevented by using a realtime listener as shown above.
 
mDatabase.child("users").child(userId).get().addOnSuccessListener { Log.i("firebase", "Got value ${it.value}") }.addOnFailureListener{ Log.e("firebase", "Error getting data", it) }
 
 

Update Data into Firebase Database

Update specific fields

  • setValue() function writes to database but also overwrite node if already exists at that path so we can use it to update data into firebase
  • push() has generate child node with unique id that we have stored with our data , so now we just have to overwrite / update that data with new data at same key / unique id with help of setValue() method
  • If you want to know when your data has been committed, you can add a completion listener. Both setValue() and updateChildren() take an optional completion listener that is called when the write has been successfully committed to the database. If the call was unsuccessful, the listener is passed an error object indicating why the failure occurred.
database.child("users").child(userId).setValue(user)     .addOnSuccessListener {         // Write was successful!         // ...     }     .addOnFailureListener {         // Write failed         // ...
 

Remove / Delete Data from Firebase Database

// class / Activity member private lateinit var databaseReference: DatabaseReference // intialize database reference databaseReference = Firebase.database.reference // provide path of data val quoteReference = databaseReference.child("quotes")
  • The simplest way to delete data is to call removeValue() on a reference to the location of that data.
  • You can also delete by specifying null as the value for another write operation such as setValue()

Detach listeners

  • Callbacks are removed by calling the removeEventListener() method on your Firebase database reference.
  • If a listener has been added multiple times to a data location, it is called multiple times for each event, and you must detach it the same number of times to remove it completely.
  • Calling removeEventListener() on a parent listener does not automatically remove listeners registered on its child nodes; removeEventListener() must also be called on any child listeners to remove the callback.