【问题标题】:How to save the data of recyclerview LiveData<List<SportData>> to avoid the loss of bottom navigation data?如何保存recyclerview LiveData<List<SportData>>的数据,避免底部导航数据丢失?
【发布时间】:2022-01-16 22:00:02
【问题描述】:

我的片段中recyclerview中的数据使用了网站的api。但是切换底部导航时数据丢失。但数据结构不是简单的 int 或 string。我应该如何将它写入 onSaveInstanceState 来存储它。以及如何让他正常恢复LiveData的数据类型?

recyclerview 的数据看起来像 viewmodel 中的那样。

private val _photos = MutableLiveData<List<SportData>>()
    val photos: LiveData<List<SportData>> get() = _photos

数据类

@Parcelize
data class SportData (
    val GymID:Int,
    val Photo1:String,
    val Name:String,
    val Address:String,
    val OperationTel:String,
    val OpenState:String, 
    val GymFuncList:String 
): Parcelable

我尝试将数据保存在 onDestroyView() 中并在 onViewCreated 中获取它。它以 null 失败。

override fun onDestroyView() {
        photos2=viewModel.photos
        super.onDestroyView()
        Log.d("aaa","destroyVIEW and ${photos2}")
    }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
   
        Log.d("aaa","=viewCreate and ${photos2}")
        if (photos2!=null){
            viewModel.saveData(photos2!!)
        }

视图模型

fun saveData(savePhoto:LiveData<List<SportData>>){
        _photos=savePhoto as MutableLiveData<List<SportData>>
    }

你好,你能帮帮我吗?谢谢

【问题讨论】:

  • 您是否考虑过在下载对象后将其保存在数据库中并使用它将数据呈现给 ui 层?
  • 当前不保存房间数据。
  • 你明白onSaveInstanceState 应该做什么吗?我想不出您需要使用它来备份 ViewModel 中的数据的任何原因。 ViewModel 将在配置更改期间比 Fragment 寿命更长,因此保存实例状态是没有意义的。
  • 我还以为是因为底部导航开关而丢失了fragment recyclerview数据。我可以用它来保存它。那么如何让fragment还是切换底部导航后刚看到的画面呢?
  • 您在使用导航组件吗?您使用的是 Navigation 2.4(当前为 2.4.0-rc01)吗?只有 Navigation 2.4 会保存和恢复每个底部导航项的状态。

标签: android kotlin android-recyclerview


【解决方案1】:

您的数据已经在 ViewModel 中。你不需要保存它。由于您的 viewModel 和 viewModel 中的数据在您的应用程序存在的同时存在,因此您不会丢失它。

当您返回列表的片段时,可能会发生重新加载,对吧?

您正在从片段中调用 viewModel 方法。此方法执行请求。

您需要做的是确保您的片段在不需要时不会调用它。

你需要做的是:

if (savedBundleState == null) { //Read this as android creating this frag for the very first time
     //Here you call viewmodel method that does the request.
}

这是第 1 部分

由于您使用的是导航组件,因此您需要对其进行设置以避免新片段杀死旧片段。

【讨论】:

  • 覆盖 fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState==null){ viewModel._photos=viewModel._photos } }。但是当片段导航回到底部时,它仍然显示一个白屏。与原图不符。
猜你喜欢
  • 1970-01-01
  • 2020-09-23
  • 2021-08-27
  • 1970-01-01
  • 2020-01-05
  • 2012-05-02
  • 2020-11-17
  • 2019-07-03
  • 1970-01-01
相关资源
最近更新 更多