Android/FireBase Series: [#03] — Firebase Realtime Database

Leo N
1 min readMar 28, 2020

--

Agenda

Android: FireBase + Kotlin Part 1 (Remote Config)

Android: FireBase + Kotlin Part 2 (Firebase Firestore)

Android: FireBase + Kotlin Part 3 (Firebase Realtime Database)

Realtime Database

api 'com.google.firebase:firebase-database-ktx:$NewestVersion'

Features

Get an instance of FirebaseDatabase

Kotlin

val database = FirebaseDatabase.getInstance()
val anotherDatabase = FirebaseDatabase.getInstance(FirebaseApp.getInstance("myApp"))

Kotlin + KTX

val database = Firebase.database
val anotherDatabase = Firebase.database(Firebase.app("myApp"))

Get the FirebaseDatabase for the specified url

Kotlin

val database = FirebaseDatabase.getInstance(url)

Kotlin + KTX

val database = Firebase.database(url)

Get the FirebaseDatabase of the given FirebaseApp and url

Kotlin

val database = FirebaseDatabase.getInstance(app, url)

Kotlin + KTX

val database = Firebase.database(app, url)

Convert a DataSnapshot to a POJO

Kotlin

val snapshot: DataSnapshot = ...
val myObject = snapshot.getValue(MyClass::class.java)

Kotlin + KTX

val snapshot: DocumentSnapshot = ...
val myObject = snapshot.getValue<MyClass>()

Convert a DataSnapshot to generic types such as List or Map

Kotlin

val snapshot: DataSnapshot = ...
val typeIndicator = object : GenericTypeIndicator<List<Message>>() {}
val messages: List<Message> = snapshot.getValue(typeIndicator)

Kotlin + KTX

val snapshot: DocumentSnapshot = ...
val messages: List<Message> = snapshot.getValue<List<@JvmSuppressWildcards Message>>()

Thanks: https://firebaseopensource.com/projects/firebase/firebase-android-sdk/docs/ktx/database.md/

--

--

Leo N
Leo N

Written by Leo N

🇻🇳 🇸🇬 🇲🇾 🇦🇺 🇹🇭 Engineer @ GXS Bank, Singapore | MSc 🎓 | Technical Writer . https://github.com/nphausg

No responses yet