GridView Adapter duplicate the same list every once I leave the fragment and re-open it again

42 Views Asked by At

Recently I noticed a problem in my app when I close viewAllfragment and re-open it again, I see the list is duplicated again and again each time with the same data, I tried to clear the list when the fragment was destroyed and submit the data only when the adapter is empty but all of this didn't fix the issue

this the XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.view_all.ViewAllFragment">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone"
        android:background="@color/lightGray"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/lightGray"
        android:verticalSpacing="1dp"
        android:horizontalSpacing="1dp"
        android:visibility="gone"
        tools:visibility="visible"
        android:numColumns="auto_fit"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

and this GridProductAdapter code

class GridProductAdapter : BaseAdapter() {

    private var productScrollModelList = arrayListOf<HorizontalProductScrollModel>()

//    init {
//
//    }

    fun submitList(productScrollModelList: List<HorizontalProductScrollModel>){
        this.productScrollModelList.addAll(productScrollModelList)
        notifyDataSetChanged()

        Log.d(TAG, "submitList: size ${productScrollModelList.size}")
    }

    fun clearList(){
        this.productScrollModelList.clear()
        notifyDataSetChanged()
    }

    override fun getCount(): Int {
        return productScrollModelList.size
    }

    override fun getItem(i: Int): Any? {
        return null
    }


    override fun getItemId(i: Int): Long {
        return 0
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        var localConvertView: View? = convertView

        val binding: HorizontalScrollItemLayoutBinding

        if (localConvertView == null) {
            binding = HorizontalScrollItemLayoutBinding.inflate(
                LayoutInflater.from(parent.context)
            )
            localConvertView = binding.root
            localConvertView.setTag(R.id.viewBinding, binding)
        } else {
            binding = localConvertView.getTag(R.id.viewBinding) as HorizontalScrollItemLayoutBinding
        }

//        binding.hsProductImage.setImageResource(productScrollModelList.get(position).getProductImage());
        Glide.with(binding.root.context)
            .load(productScrollModelList[position].productImage)
            .placeholder(R.drawable.placeholder_image)
            .into(binding.hsProductImage)
        binding.hsProductName.text = productScrollModelList[position].productName
        binding.hsProductDescription.text = productScrollModelList[position].productDescription
        binding.hsProductPrice.text = "Rs.${productScrollModelList[position].productPrice}/-"

//        binding.getRoot().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//            }
//        });
        return localConvertView
    }
}

and I use it in viewAllfragment like the following

   private var _binding: FragmentViewAllBinding? = null
    private val binding get() = _binding!!

    private val LAYOUT_CODE = 0
    private val wishList= arrayListOf<WishListModel>()

    private val wishlistAdapter = WishlistAdapter(false)

    private val args by navArgs<ViewAllFragmentArgs>()

    private var layoutCode:Int =0

    private val gridProductAdapter by lazy { GridProductAdapter()  }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentViewAllBinding.inflate(inflater)

        layoutCode = args.layoutCode
        (requireActivity() as MainActivity).fragmentTitleAndActionBar(args.title)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)



        if(layoutCode == 0) {

            wishList.addAll(args.viewAllProductList!!)

            wishlistAdapter.asyncListDiffer.submitList(wishList)
//            wishlistAdapter.submitList(wishList)

            binding.recyclerView.apply {
                visibility = View.VISIBLE
                layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
                adapter = wishlistAdapter
            }

        }else if(layoutCode == 1) {

            //================ Horizontal list ======================//

            binding.gridView.visibility = View.VISIBLE

            binding.gridView.adapter = gridProductAdapter

            Log.d(TAG, "onViewCreated: horizontalProductScrollModelList size ${args.horizontalProductScrollModelList.size}")

            if(gridProductAdapter.isEmpty) {
                gridProductAdapter.submitList(args.horizontalProductScrollModelList.toList())
            }
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        gridProductAdapter.clearList()
        _binding = null
    }
3

There are 3 best solutions below

0
Dr Mido On BEST ANSWER

I fixed the problem by clearing the args.horizontalProductScrollModelList that I got from HomeFragment before I opened the viewAllfragment

override fun onDestroyView() {
    super.onDestroyView()
   gridLayoutList.clear()
}
1
Hassaan On

Make submitList() function of your adapter like this:

fun submitList(productScrollModelList: List<HorizontalProductScrollModel>){
 this.productScrollModelList.clear()
 this.productScrollModelList.addAll(productScrollModelList)
 notifyDataSetChanged()    
 }

Clear the list before submitting new list in adapter.

2
AudioBubble On

You can also update recyclerview with new data by re-intiailing arraylist.

fun submitList(productScrollModelList: List<HorizontalProductScrollModel>){
 this.productScrollModelList= arrayListOf<HorizontalProductScrollModel>()
 this.productScrollModelList.addAll(productScrollModelList)
 notifyDataSetChanged()    
 }