androidkotlinandroid-paging-library

Android paging library show empty viewholder when list is empty


I am using paging library with recyclerView and my task is to shows empty viewHolder when I receive empty arrayList from server.

I tried to check that list is empty or not, but when I get response it calls the Observer method 2 times (1st time empty list, 2nd time real list), after when I use swipeRefresh it DataSource class sends empty list as it has same list already in cache. Also I have pagination and checking for dataset size is difficult as there are many cases.

/**
 * Simple Adapter used to show list of Appeals with pagination
 */
class MyAppealsAdapter : PagedListAdapter<Appeal, RecyclerView.ViewHolder>(diffCallBack) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return AppealsViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_my_appeal, parent, false))
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is AppealsViewHolder -> holder.bind(position)
        }
    }

    inner class AppealsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        @SuppressLint("SimpleDateFormat")
        fun bind(position: Int) {
            getItem(position)?.let { item ->
                item.fields?.get(AppealKeyObj.K_SUB_ISSUE)?.let {
                    itemView.mTypeOfAppeal.text = it
                }
            }
        }
    }

    companion object {
        open var diffCallBack: DiffUtil.ItemCallback<Appeal> = object : DiffUtil.ItemCallback<Appeal>() {
            override fun areItemsTheSame(oldItem: Appeal, newItem: Appeal): Boolean {
                return oldItem.id === oldItem.id
            }

            override fun areContentsTheSame(oldItem: Appeal, newItem: Appeal): Boolean {
                return oldItem == newItem
            }
        }
    }
}

Please help to show empty viewHolder when I receive empty arrayList

enter image description here


Solution

  • I did it like this

    override fun getItemViewType(position: Int): Int {
            return if (super.getItemCount() == 0) EMPTY else FILLED
        }
    
        override fun getItemCount(): Int {
            return if (super.getItemCount() == 0) 1 else super.getItemCount()
        }
    

    And also changed linearlayoutmanager to custom one with overriden method

    override fun onLayoutChildren(recycler: Recycler?, state: RecyclerView.State?) {
            try {
                super.onLayoutChildren(recycler, state)
            } catch (e: IndexOutOfBoundsException) {
                Timber.e(e)
            }
        }