ListAdapter获取正确的列表,但不更新值

如何解决ListAdapter获取正确的列表,但不更新值

我具有以下功能-

    private fun fetchGroupData(callback: (groupModelList: List<GroupModel>) -> Unit) {
        val groupModelList = mutableListOf<GroupModel>()
        groupViewmodel.getAllGroupEntities().observeOnce(requireActivity(),Observer { groupEntityList ->
            groupEntityList.forEach { groupEntity ->
                /*
                We iterate though all of the available groups,for each group we get all of it's groupMembers models
                */
                val groupName = groupEntity.groupName
                val groupId = groupEntity.id
                taskViewmodel.getGroupTaskCounter(groupId).observeOnce(requireActivity(),Observer { groupTaskCount ->
                    /*
                    For each group we observe it's task counter
                     */
                    groupViewmodel.getGroupMembersForGroupId(groupId).observeOnce(requireActivity(),Observer { groupMembers ->
                        /*
                        For each group,we iterate through all of the groupMembers and for each of them we use it's userId
                         to fetch the user model,getting it's full name and adding it to a list of group users full name.
                         */
                        val groupUsersFullNames = mutableListOf<String>()
                        groupMembers.forEach { groupMember ->
                            val memberId = groupMember.userId
                            groupViewmodel.getGroupParticipantForUserId(memberId).observeOnce(requireActivity(),Observer { groupUser ->
                                groupUsersFullNames.add(groupUser.fullName)
                                /*
                                When the groupUsersFullNames size matches the groupMembers size,we can add a model to our list.
                                 */
                                if (groupUsersFullNames.size == groupMembers.size)
                                    groupModelList.add(GroupModel(groupId,groupName,groupTaskCount,groupUsersFullNames))
                                /*
                                When the new list matches the size of the group list in the DB we call the callback.
                                 */
                                if (groupModelList.size == groupEntityList.size)
                                    callback(groupModelList)
                            })
                        }
                    })
                })
            }
        })
    }

以下功能正在使用-

 private fun initAdapter() {
        fetchGroupData { groupModelList ->
            if (groupModelList.isEmpty()) {
                binding.groupsListNoGroupsMessageTitle.setAsVisible()
                binding.groupsListNoGroupsMessageDescription.setAsVisible()
                return@fetchGroupData
            }
            binding.groupsListNoGroupsMessageTitle.setAsGone()
            binding.groupsListNoGroupsMessageDescription.setAsGone()
            val newList = mutableListOf<GroupModel>()
            newList.addAll(groupModelList)
            adapter.submitList(groupModelList)
            Log.d("submitList","submitList")
            binding.groupsListRecyclerview.setAdapterWithItemDecoration(requireContext(),adapter)
        }
    }

这2个函数代表从本地DB到RecyclerView中的组列表获取。

为了在创建新组时收到通知,我持有一个共享的ViewModel对象,该对象带有一个布尔值,指示是否已创建新组。

在编写这两个函数^的同一片段中,我正在观察此布尔值,如果该值为true,则会触发整个列表的重新提取-

private fun observeSharedInformation() {
        sharedInformationViewModel.value.groupCreatedFlag.observe(requireActivity(),Observer { hasGroupBeenCreated ->
            if (!hasGroupBeenCreated) return@Observer
            sharedInformationViewModel.value.groupCreatedFlag.value = false
            Log.d("submitList","groupCreatedFlag")
            initAdapter()

        })
    }

在我代码的某个片段中的某个点上,该片段中也有我的共享ViewModel的实例,我触发了Boolean LiveData的值更改-

sharedInformationViewModel.value.groupCreatedFlag.value = true

依次触发观察者,并重新获取我的群组列表。

我面临的问题是,在重新获取新列表时(因为已添加了新组),我确实获得了当前信息,并且一切都应该可以正常工作,但新数据-新创建的组-不会出现。

在2种情况下,新添加的数据均显示在列表中-

  1. 我重新启动应用
  2. 该功能再次被触发-现在发生的是,我看到具有先前新添加的组的列表,但是没有出现要添加的最新组。

此问题有一个例外-如果组列表为空,则当我与一个组一起提交列表时,确实会出现第一个要添加的组。

我想念什么?

编辑-

这是我的适配器。

我正在使用一个名为DefaultAdapterDiffUtilCallback的自定义调用,该调用需要一个模型,该模型实现一个为每个模型定义唯一ID的接口,以便我可以比较新模型和旧模型。

class GroupsListAdapter(
    private val context: Context,private val onClick: (model : GroupModel) -> Unit
) : ListAdapter<GroupModel,GroupsListViewHolder>(DefaultAdapterDiffUtilCallback<GroupModel>()) {

    override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): GroupsListViewHolder {
        val binding = GroupsListViewHolderBinding.inflate(LayoutInflater.from(context),parent,false)
        return GroupsListViewHolder(binding)
    }

    override fun onBindViewHolder(holder: GroupsListViewHolder,position: Int) {
        holder.bind(getItem(position),onClick)
    }

    override fun submitList(list: List<GroupModel>?) {
        super.submitList(list?.let { ArrayList(it) })
    }
}


/**
 * Default DiffUtil callback for lists adapters.
 * The adapter utilizes the fact that all models in the app implement the "ModelWithId" interfaces,so
 * it uses it in order to compare the unique ID of each model for `areItemsTheSame` function.
 * As for areContentsTheSame we utilize the fact that Kotlin Data Class implements for us the equals between
 * all fields,so use the equals() method to compare one object to another.
 */
class DefaultAdapterDiffUtilCallback<T : ModelWithId> : DiffUtil.ItemCallback<T>() {
    override fun areItemsTheSame(oldItem: T,newItem: T) =
        oldItem.fetchId() == newItem.fetchId()

    @SuppressLint("DiffUtilEquals")
    override fun areContentsTheSame(oldItem: T,newItem: T) =
        oldItem == newItem
}

/**
 * An interface to determine for each model in the app what is the unique ID for it.
 * This is used for comparing the unique ID for each model for abstracting the DiffUtil Callback
 * and creating a default general one rather than a new class for each new adapter.
 */
interface ModelWithId {
        fun fetchId(): String
}


data class GroupModel(val id: String,val groupName: String,var tasksCounter: Int,val usersFullNames: List<String>) : ModelWithId {

    override fun fetchId(): String = id
}


edit 2.0-

我的observeOnce()扩展名-

fun <T> LiveData<T>.observeOnce(lifecycleOwner: LifecycleOwner,observer: Observer<T>) {
    observe(lifecycleOwner,object : Observer<T> {
        override fun onChanged(t: T?) {
            observer.onChanged(t)
            removeObserver(this)
        }
    })
}

解决方法

您是否正在使用“新” ListAdapter

import androidx.recyclerview.widget.ListAdapter

在这种情况下,我可以想出您的问题的答案。但是由于我不知道您的确切实现,因此它是基于我的假设,因此您必须验证它是否适用。

为此ListAdapter,您必须实现areItemsTheSameareContentsTheSame方法。 我曾经有过类似的问题。我正在提交列表,但是它只是没有更新视图中的列表。

我可以通过仔细检查内容是否相同来进行比较来解决此问题。

对于比较功能,请考虑以下因素:

    override fun areContentsTheSame(oldItem: GroupModel,newItem: GroupModel): Boolean {
        // assuming GroupModel is a class
        // this comparison is most likely not getting the result you want
        val groupModelsAreMatching = oldItem == newItem // don't do this
        
        // for data classes it usually gives the expected result
        val exampleDataClassesMatch = oldItem.dataClass == newItem.dataClass
        // But: the properties that need to be compared need to be declared in the primary constructor
        // and not in the function body

        // compare all relevant custom properties
        val groupIdMatches = oldItem.groupId == newItem.groupId
        val groupNameMatches = oldItem.groupName == newItem.groupName
        val groupTaskCountMatches = oldItem.groupTaskCount == newItem.groupTaskCount
        val groupUsersFullNamesMatches = oldItem.groupUsersFullNames == newItem.groupUsersFullNames

        return groupIdMatches && groupNameMatches && groupTaskCountMatches && groupUsersFullNamesMatches
}

当然,您需要确保areItemsTheSame。在这里,您只需要比较groupIds。

您已经这样做了吗?

,

我发现了问题。

它与我的提取逻辑无关。

问题出在下面-

创建组时,我要向后堆栈中添加一个新的Fragment,并在完成后将其弹出。

删除群组时,我正在导航至我的主要片段,同时使用popUpTopopUpToInclusive-效果很好。

我需要使用导航,而不是向后弹出堆栈以查看新列表。

这花了我3天的时间来弄清楚。 jeez

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-