Home > OS >  How to get specific data from Firebase with Kotlin
How to get specific data from Firebase with Kotlin

Time:09-06

So I have a movie app. If I liked the movie I'm gonna save its id to firebase. And my goal is to get all movie_id's and display them on screen.

This is the saving code.

firebaseDb.getReference("Users").child(uid).child("movie")
            .push().child("movie_id")
            .setValue(args.movie.id)

And this is the firebase display

Firebase

So how to get all movie_id's? I tried this but nothing happened.

firebaseDb.getReference("Users").child(uid).child("movie").addValueEventListener(object :
ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
    val map: Map<String, Any> = snapshot.getValue() as Map<String, Any>

    val mapSize = map.keys.size
    for (i in 1..mapSize) {
        val keys = map.filterKeys { it == map.keys.toTypedArray()[i - 1] }       
    }

}

CodePudding user response:

If want to create a list of movie IDs, then use the following lines of code:

val uid = FirebaseAuth.getInstance().currentUser?.uid
val db = FirebaseDatabase.getInstance().reference
val movieRef = db.child("Users").child(uid).child("movie")
val valueEventListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        val movieIds = mutableListOf<String>()
        for (ds in dataSnapshot.children) {
            val movieId = ds.child("movie_id").getValue(String::class.java)
            movieIds.add(movieId)
        }
        Log.d("TAG", movieIds.size.toString())
    }

    override fun onCancelled(error: DatabaseError) {
        Log.d("TAG", error.getMessage()) //Never ignore potential errors!
    }
}
movieRef.addListenerForSingleValueEvent(valueEventListener)

The result in the logcat will be:

2

As I only see two movies in the screenshot.

  • Related