关于android:Kotlin和Firebase读写数据

Kotlin and Firebase read and write data

我已经学习了3个月的Kotlin,所以我想从Firebase数据库中读取数据。

这是用于写入数据的MainActivity.kt。

1
2
3
4
5
6
7
8
9
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)中调用它时。它仍然有一些问题。

1
2
3
4
5
6
7
8
9
10
11
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())
        }
    }

我的参考无法读取数据。

我得到的错误:

  • Expecting a class body

  • Too many arguments for @NonNull public open fun addValueEventListener(@NonNull p0: ValueEventListener): ValueEventListener defined in com.google.firebase.database.DatabaseReference

  • Modifier 'override' is not applicable to 'local function'

  • No type arguments expected for fun getValue(): Any?

  • Modifier 'override' is not applicable to 'local function'

  • Cannot access 'TAG': it is invisible (private in a supertype) in 'AppCompatActivity'


尝试此代码:

1
2
3
4
5
6
7
8
9
10
11
    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())
            }
        }