To use the Cloud Firestore Android SDK with Kotlin Extensions, add the following
to your app's build.gradle file:
// See maven.google.com for the latest versions
// This library transitively includes the firebase-firestore library
implementation 'com.google.firebase:firebase-firestore-ktx:$VERSION'Kotlin
val firestore = FirebaseFirestore.getInstance()
val anotherFirestore = FirebaseFirestore.getInstance(FirebaseApp.getInstance("myApp"))Kotlin + KTX
val firestore = Firebase.firestore
val anotherFirestore = Firebase.firestore(Firebase.app("myApp"))Kotlin
firestore.collection("cities")
.document("LON")
.addSnapshotListener { document: DocumentSnapshot?, error: ->
if (error != null) {
// Handle error
return@addSnapshotListener
}
if (document != null) {
// Use document
}
}Kotlin + KTX
firestore.collection("cities")
.document("LON")
.snapshots()
.collect { document: DocumentSnapshot ->
// Use document
}Kotlin
firestore.collection("cities")
.whereEqualTo("capital", true)
.addSnapshotListener { documents: QuerySnapshot?, error ->
if (error != null) {
// Handle error
return@addSnapshotListener
}
if (documents != null) {
for (document in documents) {
// Use document
}
}
}Kotlin + KTX
firestore.collection("cities")
.whereEqualTo("capital", true)
.snapshots()
.collect { documents: QuerySnapshot ->
for (document in documents) {
// Use document
}
}Kotlin
val snapshot: DocumentSnapshot = ...
val myObject = snapshot.get("fieldPath", MyClass::class.java)Kotlin + KTX
val snapshot: DocumentSnapshot = ...
val myObject = snapshot.get<MyClass>("fieldPath")Kotlin
val snapshot: DocumentSnapshot = ...
val myObject = snapshot.toObject(MyClass::class.java)Kotlin + KTX
val snapshot: DocumentSnapshot = ...
val myObject = snapshot.toObject<MyClass>()Kotlin
val snapshot: QuerySnapshot = ...
val objectList = snapshot.toObjects(MyClass::class.java)Kotlin + KTX
val snapshot: QuerySnapshot = ...
val objectList = snapshot.toObjects<MyClass>()Kotlin
val settings = FirebaseFirestoreSettings.Builder()
.setHost("10.0.2.2:8080")
.setSslEnabled(false)
.setPersistenceEnabled(false)
.build()
firestore.setFirestoreSettings(settings)Kotlin + KTX
firestore.firestoreSettings = firestoreSettings {
host = "http://10.0.2.2:8080"
isSslEnabled = false
isPersistenceEnabled = false
}