/
MainActivity.kt
52 lines (44 loc) · 1.75 KB
/
MainActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.google.firebase.referencecode.database.kotlin
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.database
import com.google.firebase.database.getValue
import com.google.firebase.Firebase
import com.google.firebase.referencecode.database.R
abstract class MainActivity : AppCompatActivity() {
companion object {
private const val TAG = "KotlinActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Reuse the layout used in MainActivity
setContentView(R.layout.activity_main)
}
fun basicReadWrite() {
// [START write_message]
// Write a message to the database
val database = Firebase.database
val myRef = database.getReference("message")
myRef.setValue("Hello, World!")
// [END write_message]
// [START read_message]
// Read from the database
myRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
val value = dataSnapshot.getValue<String>()
Log.d(TAG, "Value is: $value")
}
override fun onCancelled(error: DatabaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException())
}
})
// [END read_message]
}
}