I have a fragment (FragmentAdd) with a button which is supposed to update the RecyclerView of another fragment (FragmentHome). Why isn't the RecyclerView updated?
FragmentAdd:
saveBtn?.setOnClickListener{
arrayList = getUpdatedList()
val homeAdapter = HomeAdapter(FragmentHome(),arrayList)
homeAdapter.updateRecyclerView(arrayList)
}
FragmentHome:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_home, container, false)
recyclerView = view.findViewById(R.id.recyclerView)
recyclerView!!.setHasFixedSize(true)
recyclerView!!.layoutManager = LinearLayoutManager(context)
recyclerView!!.adapter = HomeAdapter(this, transactList)
return view
}
HomeAdapter:
fun updateRecyclerView(newList: ArrayList<Any>){
itemsList.clear()
itemsList.addAll(newList)
this.notifyDataSetChanged()
}
I think the issue might be because I'm creating another object of HomeAdapter
in FragmentAdd. If so, how should I make sure it references the original object.
CodePudding user response:
Issues seems to be the creation of multiple HomeAdapter instance.
You can create the single object using companion object
In FragmentAdd
companion object {var homeAdapter:HomeAdapter?=null}
Then FragmentAdd
homeAdapter = HomeAdapter(FragmentHome(),arrayList)
homeAdapter.updateRecyclerView(arrayList)
In FragmentHome
recyclerView!!.adapter=FragmentAdd.homeAdapter!!