使用来自AsyncTask的GSON数据实现更多加载分页

时间:2019-09-24 03:52:00

标签: android kotlin

大家好,我已经创建了RecyclerView并使用AsyncTask获取数据。第一步,我要显示10个第一个数据并加载更多10个数据,直到到达最后一个数据。 之后,我想将进度条作为页脚来加载数据。

这是我的MutationRecyclerViewAdapter代码

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_mutation, parent, false)
    return ViewHolder(view)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.mItem = mValues[position]
    holder.itemView.text_transaction_type.text = getTransactionTypeString(mValues[position].transactionType)
    holder.itemView.text_transaction_number.text = mValues[position].transactionID
    holder.itemView.text_transaction_date.text = AppUtil.getDefaultDateFormat(mValues[position].transactionDate)
    holder.itemView.text_balance.text = mValues[position].balance
    holder.itemView.text_amount.text = mValues[position].amount
    holder.itemView.text_merchant_name.text = mValues[position].merchant

    if(mValues[position].transactionType != null) {
        when (mValues[position].transactionType) {
            "PR", "ST" -> {
                holder.itemView.image_transaction_icon.setImageResource(R.drawable.ic_action_purchase)
                holder.itemView.image_transaction_icon.background = ContextCompat.getDrawable(mContext!!, R.drawable.bg_circle)
                holder.itemView.text_transaction_type.setTextColor(ContextCompat.getColor(mContext!!, R.color.orange))
                holder.itemView.text_product_name.text = holder.mItem!!.merchant
                holder.itemView.text_amount.setTextColor(ContextCompat.getColor(mContext!!, R.color.orange))
                //holder.itemView.text_product_name.visibility = View.VISIBLE
                holder.itemView.image_balance.setImageResource(R.drawable.ic_min_orange)
            }
            "RD" -> {
                holder.itemView.image_transaction_icon.setImageResource(R.drawable.ic_action_withdraw_rotated)
                holder.itemView.image_transaction_icon.background = ContextCompat.getDrawable(mContext!!, R.drawable.bg_circle)
                holder.itemView.text_transaction_type.setTextColor(ContextCompat.getColor(mContext!!, R.color.orange))
                holder.itemView.image_balance.setImageResource(R.drawable.ic_plus)
                holder.itemView.text_amount.setTextColor(ContextCompat.getColor(mContext!!, R.color.orange))
            }
            "CI" -> {
                holder.itemView.text_transaction_type.setTextColor(ContextCompat.getColor(mContext!!, R.color.green_grass_dark))
                holder.itemView.image_transaction_icon.background = ContextCompat.getDrawable(mContext, R.drawable.bg_circle_green)
                holder.itemView.image_transaction_icon.setImageResource(R.drawable.ic_action_cash_in)
                holder.itemView.image_balance.setImageResource(R.drawable.ic_plus_green)
                holder.itemView.text_amount.setTextColor(ContextCompat.getColor(mContext, R.color.green_grass_dark))
            }
            "CO", "FCO", "XX" -> {
                holder.itemView.image_transaction_icon.background = ContextCompat.getDrawable(mContext!!, R.drawable.bg_circle)
                holder.itemView.image_transaction_icon.setImageResource(R.drawable.ic_action_withdraw_rotated)
                holder.itemView.text_transaction_type.setTextColor(ContextCompat.getColor(mContext, R.color.orange))
                holder.itemView.image_balance.setImageResource(R.drawable.ic_min_orange)
                holder.itemView.text_amount.setTextColor(ContextCompat.getColor(mContext, R.color.orange))
            }
            "AD" -> {
                holder.itemView.image_transaction_icon.setImageResource(R.drawable.ic_action_adjustment)
                holder.itemView.image_transaction_icon.background = ContextCompat.getDrawable(mContext!!, R.drawable.bg_circle_gray)
                holder.itemView.text_transaction_type.setTextColor(ContextCompat.getColor(mContext, R.color.gray_dark))
                holder.itemView.image_balance.setImageResource(R.drawable.ic_plus)
                holder.itemView.text_amount.setTextColor(ContextCompat.getColor(mContext, R.color.gray_dark))

            }
            "RBY"->{
                holder.itemView.image_transaction_icon.setImageResource(R.drawable.ic_action_adjustment)
                holder.itemView.image_transaction_icon.background = ContextCompat.getDrawable(mContext!!, R.drawable.bg_circle_gray)
                holder.itemView.text_transaction_type.setTextColor(ContextCompat.getColor(mContext, R.color.gray_dark))
                holder.itemView.image_balance.setImageResource(R.drawable.ic_plus)
                holder.itemView.text_amount.setTextColor(ContextCompat.getColor(mContext, R.color.gray_dark))
            }
            "TO" -> {
                holder.itemView.image_transaction_icon.background = ContextCompat.getDrawable(mContext!!, R.drawable.bg_circle_blue)
                holder.itemView.image_transaction_icon.setImageResource(R.drawable.ic_action_transfer)
                holder.itemView.text_transaction_type.setTextColor(ContextCompat.getColor(mContext!!, R.color.blue_foreground))
                holder.itemView.image_balance.setImageResource(R.drawable.ic_minus_blue)
                holder.itemView.text_amount.setTextColor(ContextCompat.getColor(mContext, R.color.blue_foreground))

            }
            "TI", "BY" -> {
                holder.itemView.image_transaction_icon.background = ContextCompat.getDrawable(mContext!!, R.drawable.bg_circle_green)
                holder.itemView.image_transaction_icon.setImageResource(R.drawable.ic_action_transfer_in)
                holder.itemView.text_transaction_type.setTextColor(ContextCompat.getColor(mContext!!, R.color.green_grass_dark))
                holder.itemView.image_balance.setImageResource(R.drawable.ic_plus_green)
                holder.itemView.text_amount.setTextColor(ContextCompat.getColor(mContext, R.color.green_grass_dark))
            }
            else -> {
                holder.itemView.image_transaction_icon.setImageResource(R.drawable.ic_action_adjustment)
                holder.itemView.image_transaction_icon.background = ContextCompat.getDrawable(mContext!!, R.drawable.bg_circle_gray)
                holder.itemView.text_transaction_type.setTextColor(ContextCompat.getColor(mContext, R.color.gray_dark))
                holder.itemView.image_balance.visibility = View.INVISIBLE
                holder.itemView.text_amount.setTextColor(ContextCompat.getColor(mContext, R.color.gray_dark))
            }
        }
    } else {
        holder.itemView.image_transaction_icon.setImageResource(R.drawable.ic_action_adjustment)
        holder.itemView.image_transaction_icon.background = ContextCompat.getDrawable(mContext!!, R.drawable.bg_circle_gray)
        holder.itemView.text_transaction_type.setTextColor(ContextCompat.getColor(mContext, R.color.gray_dark))
        holder.itemView.image_balance.visibility = View.INVISIBLE
        holder.itemView.text_amount.setTextColor(ContextCompat.getColor(mContext, R.color.gray_dark))
    }

    holder.mView.setOnClickListener {
        mListener?.onMutationFragmentInteraction(holder.mItem!!)
    }
    holder.mView.setOnLongClickListener {
        mListener?.onLongMutationFragmentInteraction(holder.mItem!!)
        false
    }
}

private fun getTransactionTypeString(type: String): String {
    return when(type) {
        "PR" -> mContext!!.getString(R.string.purchase)
        "CI" -> mContext!!.getString(R.string.cash_in)
        "CO" -> mContext!!.getString(R.string.cash_out)
        "RD" -> mContext!!.getString(R.string.redeem)
        "TI" -> mContext!!.getString(R.string.transfer_in)
        "TO" -> mContext!!.getString(R.string.transfer_out)
        "FCO" -> mContext!!.getString(R.string.cash_out)
        "XX" -> mContext!!.getString(R.string.cash_out)
        "BY" -> mContext!!.getString(R.string.purchase)
        "ST" ->  mContext!!.getString(R.string.settlement)
        "AD" -> mContext!!.getString(R.string.adjustment)
        "RBY" ->mContext!!.getString(R.string.rby)
        else -> return type
    }
}

override fun getItemCount(): Int {
    return mValues.size
}

inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) {
    var mItem: MutationItem? = null
}

这是我的MutationFragment

private var maxItemSize = -1
private var mListener: OnMutationFragmentInteractionListener? = null
lateinit var adapter : MutationRecyclerViewAdapter
lateinit var refreshButton : ImageView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    if (arguments != null) {
        maxItemSize = arguments?.getInt(MAX_ITEMS_SIZE, -1)!!
    }
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater.inflate(R.layout.fragment_mutation, container, false)
    (activity as AppCompatActivity).supportActionBar?.title = "MutationFragment"
    return view
}

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

    MutationContent.ITEMS.clear()

    GetTransactionTask(context!!, this).execute()
    mutation_list.layoutManager = LinearLayoutManager(context)

    adapter = MutationRecyclerViewAdapter(MutationContent.getSavedTransactions(context, maxItemSize), mListener, context)

    refreshLayout.apply {
        scrollUpChild = mutation_list
        setOnRefreshListener {
            isRefreshing = false
            GetTransactionTask(context!!, this@MutationFragment).execute()
        }
    }

}

fun toggleView(isEmpty : Boolean){
    if(isEmpty){
        progress_bar?.visibility = View.GONE
        mutation_list?.visibility = View.GONE
        //refreshButton.visibility = View.GONE
        text_no_mutation?.visibility = View.VISIBLE
    }
    else{
        progress_bar?.visibility = View.GONE
        mutation_list?.visibility = View.VISIBLE
        //refreshButton?.visibility = View.GONE
        text_no_mutation?.visibility = View.GONE
    }
    activity?.invalidateOptionsMenu()
}

override fun onGetTransactionSuccess(response: ResponseRequestMutasiSaldo) {
    MutationContent.import(context, response, maxItemSize)
    adapter = MutationRecyclerViewAdapter(MutationContent.getSavedTransactions(context, maxItemSize),
            mListener, context)
    mutation_list?.adapter = adapter
    if(adapter.mValues.isEmpty()) {
        text_no_mutation?.setText(getString(R.string.no_mutation))
    } else {
        text_no_mutation?.setText(getString(R.string.load_mutation))
    }
    toggleView(adapter.mValues.isEmpty())
}

override fun onAttach(context: Context?) {
    super.onAttach(context)
    if (context is OnMutationFragmentInteractionListener) {
        mListener = context
    } else {
        throw RuntimeException(context!!.toString() + " must implement OnSettingFragmentInteractionListener")
    }
}

override fun onDetach() {
    super.onDetach()
    mListener = null
}

override fun onTransactionFailed(response: ResponseRequestMutasiSaldo) {
    adapter = MutationRecyclerViewAdapter(
            MutationContent.getSavedTransactions(context, maxItemSize),
            mListener, context)
    mutation_list?.adapter = adapter
    toggleView(adapter.mValues.isEmpty())
    /*if(activity != null)
        Toasty.error(activity!!,response.errorMessage).show()*/
}

interface OnMutationFragmentInteractionListener {
    fun onMutationFragmentInteraction(item: MutationItem)
    fun onLongMutationFragmentInteraction(item: MutationItem)
}

companion object {
    val MAX_ITEMS_SIZE = "MAX_ITEM_SIZE"
}

这是我的Asynctask类

override fun doInBackground(vararg p0: Void?): ResponseRequestMutasiSaldo? {
    return ResourceService(context).requestMutasiSaldo()
}

override fun onPostExecute(result: ResponseRequestMutasiSaldo?) {
    if(result != null && (result.error.equals(AppUtil.RESPONSE_ERROR_CODE_EXPIRY) || result.success.equals(AppUtil.RESPONSE_SUCCESS_CODE_EXPIRY))){
        EventBus.getDefault().post(SessionExpiry(result.message?:""))
        return
    }
    if(result != null && result.success.equals("1")) {
        listener.onGetTransactionSuccess(result)
    }
    if(result != null && result.error.equals("1")){
        listener.onTransactionFailed(result)
        return
    }
}

我已经成功地从Web服务获取了所有数据,现在我已经尝试过使用documentation这样的EndlessRecyclerViewListener并使用多个引用来实现我的任务。但是功能AddOnScroll不能正常工作,我也不怎么理解它是如何工作的。如果要使用EndlessRecyclerViewListener,该怎么办?还是有其他方法可以在不使用EndlessRecyclerViewListener类的情况下实现这一目标?

1 个答案:

答案 0 :(得分:0)

使用addOnScrollListener进行此操作。

val pageLimit: Int = 10//row returned each time on scroll
var noMoreItems: Boolean = false

像这样在您的回收视图中使用addOnScrollListener

dataRecyclerView.addOnScrollListener(object : androidx.recyclerview.widget.RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: androidx.recyclerview.widget.RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)

                if (!recyclerView.canScrollVertically(1)) {
                    if (!utility.isConnected(mContext)) {
                        Toast.makeText(mContext, "No internet", Toast.LENGTH_SHORT).show()
                        return
                    }

                    if (noMoreItems)
                        return
                    val lastPage: String
                    val nextPage: Int
                    if (dataArrayList.size > 0) {
                        lastPage = ((dataArrayList.size - 1) / pageLimit).toInt().toString()
                        nextPage = Integer.parseInt(lastPage) + 1
                    } else {
                        nextPage = 1;
                    }
                    loadRecords(nextPage.toString())
                }
            }
        })

loadRecords()中,您应该使用页码呼叫asynctask。 返回的行数少于noMOreItems=true时,请设置pageLimit