在我的项目中,我有一个字符串列表。我要将此列表保存到共享首选项。有人能帮上忙吗?
data class select(
@SerializedName("items")
var items: MutableList<String>?=null
)发布于 2020-01-21 18:05:53
您可以使用Gson将列表作为Json文本存储在SharedPreference中,然后进行相应的操作
//saving list in Shared Preference
fun setLists(list:ArrayList<String>){
val gson = Gson()
val json = gson.toJson(list)//converting list to Json
editor.putString("LIST",json)
editor.commit()
}
//getting the list from shared preference
fun getList():ArrayList<String>{
val gson = Gson()
val json = preferences.getString("LIST",null)
val type = object :TypeToken<ArrayList<String>>(){}.type//converting the json to list
return gson.fromJson(json,type)//returning the list
}不要忘记在应用程序级别的gradle文件中实现Gson库
https://stackoverflow.com/questions/59833688
复制相似问题