X-Black...
X-Black...

Reputation: 1596

RecyclerView only populates data from ViewModel after the orientation changes

I'm using NavigationDrawer and trying out the MVVM architecture, all layouts were fine, then i implemented a RecyclerView that displays data from Firebase in one of the fragments.

No errors are displayed, but the RecyclerView doesn't populate data. I added logging to the app, found out the adapter returns the size, the data != null, but interestingly the recyclerView populates data only on device configuration changes, such as device orientation

Switching between fragments and coming back to the RecyclerView fragment: same problem again until I rotate the device

1 2 3 on switching back after switching back

I've tried:

HomeFragment

...
class HomeFragment : Fragment() {

    private lateinit var homeViewModel: HomeViewModel

    lateinit var recyclerView: RecyclerView

    lateinit var swipeRefresh: SwipeRefreshLayout

    lateinit var postAdapter: PostAdapter

    val viewModelFactory = HomeViewModelFactory()



    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {

        val view = inflater.inflate(R.layout.fragment_home, container, false)
    homeViewModel = ViewModelProviders.of(this, viewModelFactory).get(HomeViewModel::class.java)


        recyclerView  = view.findViewById(R.id.post_recycler_view)
        recyclerView.setHasFixedSize(true)
        val linearLayoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, true)
        linearLayoutManager.stackFromEnd = true

        recyclerView.layoutManager = linearLayoutManager

        // Observe the model
        homeViewModel.postList.observe(this@HomeFragment, Observer { posts ->

            postAdapter = PostAdapter(context!!, posts)
            recyclerView.adapter = postAdapter
            postAdapter.notifyDataSetChanged()

            homeViewModel.myRef.keepSynced(true)
        })

        swipeRefresh = view.findViewById(R.id.swiperefresh)

        swipeRefresh.setOnRefreshListener {

            Toast.makeText(context, " Adapter size: ${postAdapter.itemCount}", Toast.LENGTH_LONG).show() // works : returns 12
            println("list:${homeViewmodel.postList.value} ") works : prints data

            swipeRefresh.isRefreshing = false
        }

        return view
    }

viewModel

class HomeViewModel() : ViewModel() {

var postList = loadPosts()

fun loadPosts(): MutableLiveData<MutableList<Post>> {

        val postList = mutableListOf<Post>()
        val l_postList = MutableLiveData<MutableList<Post>>()

        firebaseRepo.retrievePosts(postList)

       l_postList.value =  postList


        return l_postList
    }
}

firebaseRepo

       fun retrievePosts(postList: MutableList<Post>) {

        val postsRef = ref.child("Posts")

        postsRef.addValueEventListener(object : ValueEventListener{
            override fun onCancelled(p0: DatabaseError) {}

            override fun onDataChange(p0: DataSnapshot) {
                postList.clear()

                for(snapshot in p0.children){
                    val post = snapshot.getValue(Post::class.java)

                    postList.add(post!!)


                    }
                }
        })
    }

Upvotes: 1

Views: 465

Answers (1)

Ryan M
Ryan M

Reputation: 20147

Your retrievePosts method is only changing the MutableList<Post> in postList, rather than the MutableLiveData<MutableList<Post>> in l_postList, so the RecyclerView is never notified of the change. MutableLiveData can only detect changes that occur via setting its value.

You should update the retrievePosts method to take a reference to the MutableLiveData and set the value of that MutableLiveData on changes.

Upvotes: 1

Related Questions