NotifyDataSet Changed Android - Recycler View Adapter

69 Views Asked by At
    val recyclerView = findViewById<RecyclerView>(R.id.rv)
    val adapter = UserDetailsAdapter(users)
    recyclerView.adapter =adapter
    recyclerView.layoutManager= LinearLayoutManager(this)
    Thread{
        userDao.insertAll(user,user2,user3)
        users= userDao.getAll() as ArrayList
        Log.d("Checking Service",users.size.toString())
        recyclerView.post {
            Log.d("Checking Service","Data set Changed")
            adapter.notifyDataSetChanged()
        }
    }.start()

Here recycler view in the UI does not updating the items . runOnUIThread also tried but not working.

kindly explain why notify data set changed not working. and tell me how to update recycler view adapter from another thread.

2

There are 2 best solutions below

0
Mandeep Singh On BEST ANSWER

You need to update the users data inside the adapter before actually calling notifyDataSetChanged(). In your case you need to update the data source which you initialised in adapter constructor .

0
M000 On

add this function to your adapter instead of calling notify adapter change from activity

fun updateAdapter(users: ArrayList<User>) {
        this.users= users
        notifyDataSetChanged()
    }

and call this function

adapter.updateAdapter(users)