You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Loader如何在配置变更中存活?旋转设备后数据如何恢复?

How to Retrieve Previously Loaded Data When Loader Gets Cleared After Device Rotation?

Great question! Let's break this down clearly first, then dive into solutions:

First, a key clarification: Device rotation (a standard configuration change) doesn’t actually clear the Loader in most cases. The LoaderManager retains the Loader instance during rotation, and when your new Activity/Fragment is created, it automatically reattaches to the existing Loader—you’ll get the already loaded data immediately without reloading. That’s one of Loaders’ core design benefits.

But if we’re talking about edge cases where the Loader does get cleared (like when the Activity is truly destroyed, not just recreated, and the Loader is cleaned up along with it), here are reliable ways to retrieve your data:

  • Switch to ViewModel (Google’s Recommended Replacement)
    ViewModels are built specifically to survive configuration changes and hold UI-related data. Instead of relying on Loader persistence, store your loaded data in a ViewModel. When your Activity/Fragment is recreated after rotation, you can fetch the same ViewModel instance and access the preloaded data directly. Here’s a quick Kotlin example:

    class MyDataViewModel : ViewModel() {
        val loadedData = MutableLiveData<YourDataType>()
    
        fun fetchData() {
            // Your data loading logic here; update loadedData when complete
        }
    }
    
    // In your Activity/Fragment
    val viewModel = ViewModelProvider(this)[MyDataViewModel::class.java]
    viewModel.loadedData.observe(this) { data ->
        // Update your UI with the retrieved data
    }
    
  • Persist Data Locally
    For data that needs to survive even if the Loader (or entire app process) gets wiped, persist it to local storage. Choose the right option based on your data type:

    • Room Database (for structured, queryable data)
    • SharedPreferences (for small key-value pairs)
    • Local files (for larger or unstructured data)
      When your Activity/Fragment recreates, first check local storage for existing data—use that to populate your UI before triggering a new fetch.
  • Save Lightweight Data in onSaveInstanceState
    For small datasets, you can save data in the Activity’s onSaveInstanceState bundle. This bundle is retained during configuration changes and passed to the new instance. Note this only works for lightweight data (the bundle has size limits):

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        // Ensure YourDataType implements Parcelable or Serializable
        outState.putParcelable("cached_data", yourLoadedData)
    }
    
    // In onCreate or onRestoreInstanceState
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        savedInstanceState?.getParcelable<YourDataType>("cached_data")?.let { cachedData ->
            // Use this cached data to restore your UI
        }
    }
    

To sum up: For most rotation scenarios, Loaders handle data persistence automatically. If you’re facing cases where Loaders get cleared, ViewModel is the cleanest, most maintainable solution, with local persistence as a fallback for long-term data retention.

内容的提问来源于stack exchange,提问作者Aravind Pulagam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:34:38