Kotlin 和 Firebase 读写数据 [英] Kotlin and Firebase read and write data
问题描述
我已经学习了 3 周的 Kotlin,所以我想从我的 Firebase 数据库中读取数据.
I have learned Kotlin for 3 weeks so I would like to read the data from my Firebase database.
这是写入数据的 MainActivity.kt.
This is the MainActivity.kt to write the data.
val database = Firebase.database
val latitude = latitude.text.toString().toDouble()
val reflatitude = database.getReference("/user/time/$currenttime/latitude")
//saved location to the Firebase Database
reflatitude.setValue(latitude)
.addOnSuccessListener {
Log.d("MainActivity", "Saved the diary latitude to Firebase Database")
}
它运行良好,但是当我想从另一个活动(例如 MapActivity)调用它时.它仍然存在一些问题.
It worked well, but when I want to call it from another activity such as MapActivity. It still have some problems.
val database = Firebase.database
val reflatitude = database.getReference("/user/time/$currenttime/latitude")
reflatitude.addValueEventListener(object :ValueEventListener){
override fun onDataChange(dataSnapshot: DataSnapshot){
val latitude= dataSnapshot.getValue<Double>()
}
override fun onCancelled(error: DatabaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException())
}
}
我的 Ref 无法读取数据.
My Ref does not work in reading the data.
我得到的错误:
期待一个类体
Expecting a class body
@NonNull public open fun addValueEventListener(@NonNull p0: ValueEventListener) 的参数太多:在 com.google.firebase.database.DatabaseReference 中定义的 ValueEventListener
Too many arguments for @NonNull public open fun addValueEventListener(@NonNull p0: ValueEventListener): ValueEventListener defined in com.google.firebase.database.DatabaseReference
修饰符 'override' 不适用于 'local function'
Modifier 'override' is not applicable to 'local function'
对于 fun getValue() 没有预期的类型参数:有吗?
No type arguments expected for fun getValue(): Any?
修饰符 'override' 不适用于 'local function'
Modifier 'override' is not applicable to 'local function'
无法访问TAG":它在AppCompatActivity"中是不可见的(在超类型中是私有的)
Cannot access 'TAG': it is invisible (private in a supertype) in 'AppCompatActivity'
推荐答案
试试这个代码:
val database = Firebase.database
val reflatitude = database.getReference("/user/time/$currenttime/latitude")
reflatitude .addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot){
val latitude= dataSnapshot.getValue<Double>()
}
override fun onCancelled(error: DatabaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException())
}
}
这篇关于Kotlin 和 Firebase 读写数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!