Android Kotlin实现Paging 3时适配器无数据加载显示的问题求助
Android Paging 3 接入故障排查
故障现象
- 接入Paging 3实现分页功能后,数据完全无法在RecyclerView中展示
- 适配器的
onCreateViewHolder、onBindViewHolder方法中添加的日志无任何输出 - 代码逻辑参照官方教程编写,自认为和示例实现完全一致
- 对PagingData流的流转逻辑、
submitData的协程作用域配置不熟悉,无法定位数据中断节点
问题代码模块
Fragment 层实现
transactionsAdapterPaging = TransactionsPagedListAdapter() homeFragmentDataBinding.transactionsRV.apply { layoutManager = LinearLayoutManager(requireContext()) setHasFixedSize(true) adapter = transactionsAdapterPaging } homeFragmentDataBinding.transactionsRV.adapter = transactionsAdapterPaging lifecycleScope.launch { mainViewModel.getDataFromRemote().collectLatest { Log.e(TAG, "initializeTransactionAdapter: ++++++++====== " + it.toString()) transactionsAdapterPaging.submitData(it) } }
ViewModel 层实现
private var currentSearchResult: Flow<PagingData<TransactionDetail>>? = null fun getDataFromRemote(): Flow<PagingData<TransactionDetail>> { val lastResult = currentSearchResult val newResult: Flow<PagingData<TransactionDetail>> = mainRepository.getDataFromRemote() .cachedIn(viewModelScope) currentSearchResult = newResult return newResult }
Repository 层实现
fun getDataFromRemote(): Flow<PagingData<TransactionDetail>> { return Pager( config = PagingConfig(pageSize = 1, enablePlaceholders = false), pagingSourceFactory = { TransactionsDataSource() } ).flow }
PagingSource 实现
class TransactionsDataSource() : PagingSource<Int, TransactionDetail>() { private val TAG = "UserDataSource" override suspend fun load(params: LoadParams<Int>): LoadResult<Int, TransactionDetail> { val position = params.key ?: 1 return try { lateinit var transactionDetail: List<TransactionDetail> var response: Response<Any?>? = NewAPIServiceClient.getAllTransactionsPaging( Application.getInstance(), Prefs.getString(Constants.CARD_UUID_IN_USE, ""), position, null ) Log.e(TAG, "load: " + response) if (response != null && response.isSuccessful) { if (response?.body() != null) { val gson = Gson() try { val jsonObject1 = JSONObject(gson.toJson(response?.body())) val transactionsGson = jsonObject1.getJSONArray(Constants.PN_DATA_NEW) transactionDetail = gson.fromJson( transactionsGson.toString(), object : TypeToken<List<TransactionDetail>?>() {}.type ) } catch (e: Exception) { } } } val repos = transactionDetail Log.e(TAG, "load: ===== " + repos.toString()) return LoadResult.Page( data = repos, prevKey = if (position == 1) null else position - 1, nextKey = if (repos.isEmpty()) null else position + 1 ) } catch (exception: IOException) { Log.e(TAG, "load: 11111111111111111 " + exception) LoadResult.Error(exception) } catch (exception: HttpException) { Log.e(TAG, "load: 11111111111111111 " + exception) LoadResult.Error(exception) } } }
适配器实现
class TransactionsPagedListAdapter() : PagingDataAdapter<TransactionDetail, RepoViewHolder>(DIFF_CALLBACK) { private val TAG = "AdapterPaging" private var serviceListFiltered: List<TransactionDetail>? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RepoViewHolder { Log.e(TAG, "onCreateViewHolder: ") val itemBinding: RvListItemTransactionsHomeBinding = RvListItemTransactionsHomeBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return RepoViewHolder(itemBinding) } override fun onBindViewHolder(holder: RepoViewHolder, position: Int) { Log.e(TAG, "onBindViewHolder: ") val repoItem = getItem(position) if (repoItem != null) { (holder).bind(repoItem, position) } } override fun getItemCount(): Int { return if (serviceListFiltered == null) { 0 } else serviceListFiltered!!.size } companion object { val DIFF_CALLBACK = object : DiffUtil.ItemCallback<TransactionDetail>() { override fun areItemsTheSame(oldItem: TransactionDetail, newItem: TransactionDetail) = oldItem.uuid == newItem.uuid override fun areContentsTheSame( oldItem: TransactionDetail, newItem: TransactionDetail ) = oldItem == newItem } } } class RepoViewHolder internal constructor(itemBinding: RvListItemTransactionsHomeBinding) : RecyclerView.ViewHolder(itemBinding.root), View.OnClickListener { private val mDataBinding: RvListItemTransactionsHomeBinding = itemBinding var rootView: View fun bind(invoice: TransactionDetail, position: Int) { rootView.transaction_text_title.text = invoice.merchant?.merchantName var amountWithSymbol = Utilities.getFormattedAmount( Application.getInstance()?.applicationContext, invoice.amount.toString() ) rootView.transaction_amount.text = amountWithSymbol rootView.transactions_date.text = invoice.timestamp } override fun onClick(view: View) { if (adapterPosition > RecyclerView.NO_POSITION) { } } init { val itemView: View = itemBinding.root rootView = mDataBinding.constraintContainer itemView.setOnClickListener(this) } }
核心故障定位
- 适配器不当重写
getItemCount()方法PagingDataAdapter内部已经维护了全量加载数据的计数逻辑,代码中重写该方法返回的是从未赋值的serviceListFiltered列表长度,该值永远为0。这直接导致RecyclerView判定适配器无有效条目,不会触发ViewHolder创建和绑定流程,完全匹配“适配器无任何日志输出”的现象。 - PagingSource 异常分支缺失返回语句
两个catch分支仅创建了LoadResult.Error实例,没有通过return将结果返回给Paging框架;同时JSON解析的空catch块未给lateinit修饰的transactionDetail赋值,在接口请求失败、解析异常时,会触发未初始化属性崩溃,导致整个load流程失败。 - Fragment 数据流收集未绑定视图生命周期
直接使用lifecycleScope.launch收集PagingData流,没有关联viewLifecycleOwner的生命周期。Fragment视图销毁重建时会出现数据流泄漏、重复提交数据的问题;submitData是长生命周期的挂起函数,作用域不匹配会导致和适配器的联动失效。 - ViewModel 数据流缓存逻辑冗余
代码中声明了currentSearchResult缓存变量但未实现实际的缓存判断逻辑,每次调用getDataFromRemote()都会生成新的Pager实例和对应的PagingSource,中断之前已经启动的数据流。
修复方案
- 删除适配器中重写的
getItemCount()方法,移除未使用的serviceListFiltered变量,计数逻辑完全交由PagingDataAdapter内部实现处理 - 修正PagingSource的分支逻辑:给所有catch分支补充return语句,在JSON解析的异常分支给
transactionDetail赋值空列表,避免未初始化属性崩溃 - 修改Fragment的数据流收集逻辑,绑定视图生命周期:
viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainViewModel.getDataFromRemote().collectLatest { Log.e(TAG, "接收到分页数据: $it") transactionsAdapterPaging.submitData(it) } } } - 简化ViewModel的数据流逻辑,移除冗余的
currentSearchResult缓存变量,直接返回经过cachedIn处理的Flow即可 - 调整PagingConfig配置,将
pageSize设置为合理值(通常为20),同步设置prefetchDistance为pageSize的2倍,避免过度频繁的网络请求
内容的提问来源于stack exchange,提问作者Anshuman Patel
相关产品推荐
相关产品推荐

