如何使用SharedPreferences保存MutableList?

时间:2019-04-17 18:27:39

标签: android kotlin sharedpreferences

我想在我的Android应用中使用MutableList保存并获取SharedPreferences

我尝试过,但这是不正确的:

private fun saveFavorite(saveFavorite : MutableList<String>) {
    val sharedPref = this.getPreferences(Context.MODE_PRIVATE) ?: return
    with(sharedPref.edit()) {
        putStringSet("lastFavorite",saveFavorite)
        apply()
    }
}

1 个答案:

答案 0 :(得分:3)

putStringSet()收到Set<String>,您可以将MutableList<String>转换为设置为:

putStringSet("lastFavorite", saveFavorite.toSet())

然后,您可以在检索到它时将其转换回MutableList<String>

getStringSet("lastFavorite", setOf<String>()).toMutableList()

请注意,使用StringSet 读回时不会保留元素的顺序,因为SharedPreferences使用HashSet。另外,它不支持重复的元素

如果您的用例需要存储支持重复元素的有序列表,请考虑将其编组并将其保存为单个字符串。

例如,使用不会包含在字符串中的字符作为分隔符将所有字符串连接在一起(例如|)。然后,您可以split()将它们分开读回。

如果列表太长,则应考虑使用其他数据存储。