Kotlin和Firebase读写数据 [英] Kotlin and Firebase read and write data

查看:268
本文介绍了Kotlin和Firebase读写数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经学习了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())
        }
    }

我的参考无法读取数据.

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'

没有有趣的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆