user11971743
user11971743

Reputation:

Kotlin and Firebase read and write data

I have learned Kotlin for 3 weeks so I would like to read the data from my Firebase database.

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")
        }

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.

The errors I get:

  • 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'

Upvotes: 2

Views: 6087

Answers (1)

MMG
MMG

Reputation: 3268

Try this code:

    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())
            }
        }

Upvotes: 2

Related Questions