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

Xamarin Android:ListView页面切换后数据丢失,如何存储数据?

Fixing Empty ListView After Navigating Back in Your Android App

Hey there! I get why this is frustrating—you parse your JSON data into the ListView, switch pages, come back, and poof, it's gone. Let's break down why this happens and how to fix it.

Why Does This Happen?

When you navigate away from your Activity/Fragment and come back, Android might destroy and recreate that component (especially if the system needs resources, or even just during normal navigation in some cases). Your propertyList variable is tied to the lifecycle of that component, so when it gets recreated, the list is reset to empty unless you've stored it somewhere persistent.

Solutions to Store Your ListView Data

Here are the most common and effective ways to keep your data around:

1. Use ViewModel (Recommended for Lifecycle-Safe Data)

ViewModel is part of Android's Architecture Components, and it's designed specifically to hold data that survives configuration changes and component recreation. It's the cleanest approach here.

First, create a ViewModel class:

import androidx.lifecycle.ViewModel

class ProductViewModel : ViewModel() {
    var productList: List<products>? = null
}

(Note: Make sure your products class is structured properly—serializable or parcelable isn't strictly required here, but it helps with other use cases.)

Then, in your Activity/Fragment:

// Get the ViewModel instance
val viewModel = ViewModelProvider(this)[ProductViewModel::class.java]

// When you parse your JSON data:
val propertyList = JsonConvert.DeserializeObject<List<products>>(property.ToString())
viewModel.productList = propertyList // Store it in the ViewModel

// When you need to populate the ListView (like in onCreate or onResume):
viewModel.productList?.let { list ->
    // Your adapter setup code here, using 'list' as the data source
}

Now, even if your Activity is recreated when you navigate back, the ViewModel will retain the productList for you.

2. Save Data to Instance State

If you only need to retain data during temporary component destruction (like screen rotation or short navigation), you can use onSaveInstanceState:

In your Activity:

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    // Convert your list to a JSON string to store in the bundle
    val json = JsonConvert.SerializeObject(viewModel.productList)
    outState.putString("PRODUCT_LIST", json)
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // Restore the data if it exists
    savedInstanceState?.getString("PRODUCT_LIST")?.let { json ->
        val restoredList = JsonConvert.DeserializeObject<List<products>>(json)
        viewModel.productList = restoredList
        // Repopulate your ListView here
    }
}

Note: This isn't ideal for large datasets, as Bundle has size limits. Stick with ViewModel for most cases.

3. Local Persistence (For Long-Term Storage)

If you want the data to survive app restarts, use local storage options:

  • SharedPreferences: Good for small datasets. Serialize your list to JSON and save it as a string.
  • Room Database: Perfect for structured, larger datasets. You can save your products objects directly and query them when you need to repopulate the ListView.

For example, with SharedPreferences:

// Save the list
val prefs = getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
val json = JsonConvert.SerializeObject(propertyList)
prefs.edit().putString("PRODUCT_LIST", json).apply()

// Restore the list when needed
val savedJson = prefs.getString("PRODUCT_LIST", null)
if (savedJson != null) {
    val restoredList = JsonConvert.DeserializeObject<List<products>>(savedJson)
    // Populate ListView
}

4. Global Application Class (Use Sparingly)

You can store the list in a custom Application class, which stays alive for the entire app lifecycle. But be careful—this can lead to memory leaks if not handled properly, and it's not the most modular approach.

class MyApp : Application() {
    companion object {
        var globalProductList: List<products>? = null
    }
}

Then set MyApp.globalProductList = propertyList after parsing, and retrieve it when needed. Again, this is a quick fix but not recommended for production apps.

Which One Should You Choose?

  • Use ViewModel if you just need to retain data during navigation/configuration changes (this is the best practice).
  • Use Room/SharedPreferences if you need the data to persist across app restarts.
  • Avoid the global Application class unless it's a tiny app with simple data needs.

Give ViewModel a try first—it'll solve your immediate problem and keep your code clean!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:00:10