Home > Enterprise >  notifyDataSetChanged() is not working when observer list update data
notifyDataSetChanged() is not working when observer list update data

Time:06-24

When i observe data from observer list notifyDataSetChanged() is not working help will appreciated

categoryModel.mainCategoryList.observe(requireActivity()) {
        when (it.status) {
            Status.SUCCESS -> {if (it.data?.statusCode == 200) {
                    viewBinding.shimmerViewContainer.visibility = View.GONE
                    viewBinding.shimmerViewContainer.stopShimmer()
                    categoryList = ArrayList()
                    categoryList.addAll(it.data.ListOfMainCategories)
                    categoryAdapter.notifyDataSetChanged()

               } else {
              Toast.makeText(requireActivity(), it.data?.message,Toast.LENGTH_LONG).show()
           }}

            Status.LOADING -> {}

            Status.ERROR -> {}
        }
    }

CodePudding user response:

Side note: you need to use viewLifecycleOwner instead of requireActivity() as your observer, or else you'll leak your entire Fragment and possibly stop receiving updates in your on-screen views after a configuration change.

Your current issue: you are not changing the list that the adapter is using. You put your data in a brand new ArrayList that you assign to the categoryList property, but the Adapter won't know about that change...it will still be using whatever list reference it already had (unless you have spaghetti code and the Adapter is using a Fragment property to query the categoryList property in the Fragment).

I can't tell you exactly how to fix it without seeing the code of your Adapter.

CodePudding user response:

the problem was that once create a arrayList and pass its reference to adapter and when in observer data pass to new created arrayList but Adapter have the reference of old arrayList so it could not notify to adapter

inside observer Just clear ArrayList and reassign data to it and notifyDataSetChange is working ....

  • Related