Search code examples
androidfirebasefirebase-realtime-databaseadapter

How can I get data to put into an ArrayList using two Firebase ValueEventListeners?


This is just simple app for music. When searching in the SearchActivity, I want the composer's name and song title to be searched and listed together. Here is my Realtime Database in Firebase.

- Artists
    - 1
        - image : "Maroon 5's image"
        - name : "Maroon 5"
    - 2
        - image : "Ruel's image_2"
        - name : "Ruel"
    ...

- Songs
    - 1
        - album : "Speak Your Mind (Deluxe)"
        - image : "album's image"
        - name : "Anne-Marie"
        - title : "2002"
        - url : "song's url"
    - 2
        - album : "On My Way"
        - image : "album's image"
        - name : "Alan Walker & Sabrina Carpenter & Farruko"
        - title : "On My Way"
        - url : "song's url"
    ...

I tried to access those two databases in android studio, but the data result in ArrayList(=array) was always null. Here is my kotlin code in SearchActivity when click the button SEARCH.

FirebaseDatabase.getInstance().getReference("Artists").addListenerForSingleValueEvent(object : ValueEventListener {
    override fun onCancelled(p0: DatabaseError) {

    }

    override fun onDataChange(p0: DataSnapshot) {
        for (artist in p0.children) {
            val model = artist.getValue(Artist::class.java)
            model?.let { array.add(Model(it)) }
        }
    }
})

FirebaseDatabase.getInstance().getRefernce("Songs").addListenerForSingleValueEvent(object : ValueEventListner {
    override fun onCancelled(p0: DatabaseError) {

    }

    override fun onDataChanged(p0: DataSnapshot) {
        for (song for p0.children) {
            val model = song.getValue(Song::class.java)
            model?.let { array.add(Model(it)) }
        }
    }
})

adapter = SearchAdapter(this@SearchActivity, array)
recyclerView.adapter = adpater

Is it possible to access two databases and get an array value without a null value? I know that onDatachanged() happens late, but is it possible to put the value in the array and then put it in the adapter? I would appreciate it if you let me know in Java or Kotlin.


Solution

  • Oh! I'm sorry; I got a solution. Solution is just add adapter.notifyDataSetChange()```` in allonDataChange()``` method. In this way, I can get data from two database in firebase. Thank you for all your comment!