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

如何让SharedPreferences保持数据的插入顺序进行存储与读取?

解决SharedPreferences无法保持插入顺序的问题

SharedPreferences内部使用HashMap存储键值对,而HashMap是无序集合,调用all方法返回的Map不会保留数据的插入顺序,这就是你重启应用后读取数据顺序混乱的根本原因。

下面提供两种可行的解决方案:

方案一:单独存储插入顺序的键列表(推荐)

通过维护一个有序的键列表(用JSON数组存储),每次添加数据时更新这个列表,读取时按列表顺序取值,就能严格保持插入顺序。

添加数据代码:

// 更新本地数组和适配器
tab.add(textToShow)
customadapter.notifyDataSetChanged()

val editor = mysharedpreferences.edit()
// 保存键值对
editor.putString(textToShow, textToShow)

// 读取当前的键顺序列表,添加新键后转成JSON保存
val currentKeys = run {
    val keysJson = mysharedpreferences.getString("keys_order", "[]") ?: "[]"
    val jsonArray = JSONArray(keysJson)
    mutableListOf<String>().apply {
        for (i in 0 until jsonArray.length()) {
            add(jsonArray.getString(i))
        }
    }
}
currentKeys.add(textToShow)
editor.putString("keys_order", JSONArray(currentKeys).toString())

editor.apply()

读取数据代码:

mysharedpreferences = getSharedPreferences(fileName, MODE_PRIVATE)
tab.clear()

// 读取键顺序的JSON数组
val keysJson = mysharedpreferences.getString("keys_order", "[]") ?: "[]"
val jsonArray = JSONArray(keysJson)

// 按顺序遍历键,取出对应值
for (i in 0 until jsonArray.length()) {
    val key = jsonArray.getString(i)
    mysharedpreferences.getString(key, "")?.let {
        tab.add(it)
    }
}

// 更新适配器
customadapter.notifyDataSetChanged()
thelistv.adapter = customadapter

方案二:使用带递增索引的键名

给每个数据项分配一个递增的索引,用item_索引值作为键名,同时存储当前最大索引,读取时按索引顺序取值。

添加数据代码:

// 更新本地数组和适配器
tab.add(textToShow)
customadapter.notifyDataSetChanged()

val editor = mysharedpreferences.edit()
// 获取当前最大索引,首次为-1
val maxIndex = mysharedpreferences.getInt("max_index", -1)
val newIndex = maxIndex + 1

// 保存带索引的键值对,更新最大索引
editor.putString("item_$newIndex", textToShow)
editor.putInt("max_index", newIndex)

editor.apply()

读取数据代码:

mysharedpreferences = getSharedPreferences(fileName, MODE_PRIVATE)
tab.clear()

val maxIndex = mysharedpreferences.getInt("max_index", -1)
// 从0到最大索引依次取值
for (i in 0..maxIndex) {
    mysharedpreferences.getString("item_$i", "")?.let {
        tab.add(it)
    }
}

// 更新适配器
customadapter.notifyDataSetChanged()
thelistv.adapter = customadapter

注意事项:

  • 方案一适合需要支持删除操作的场景,删除数据时只需从键列表中移除对应键即可;
  • 方案二删除数据后会出现索引空缺,若要保持连续索引,需要重新整理所有键名,操作较繁琐;
  • 若数据量较大或需要更复杂的操作,建议使用Room数据库或直接存储JSON数组到文件,比SharedPreferences更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:35:22