英文:
How to save daily data using SharedPreferences in android app?
问题
我想保存数据(离线),我每天都会添加数据,数据会是数字,同时我也想保留以前的数据。
例如:每天保存咖啡杯的数量并存储这些数据。
那么,如何使用SharedPreferences保存它(使用Java)?
我不知道如何准确地处理这个问题。(因为我对SharedPreferences不太了解)
英文:
I want to save data (offline) which I would add daily and will be in number, while I want to keep previous data too.
for example: keeping a daily count of coffee cups and store that data.
So, How do I save it using SharedPreferences (using java)?
I don't know how to exactly approach this. (as I am not that much aware about SharedPreferences)
答案1
得分: 1
如果您想在SharedPreferences中保存一个数据列表,您可以创建一个包含您的模型的列表,并使用Gson进行序列化和反序列化,以将数据保存在SharedPreferences中。下面是一个快速的示例:
您的模型:
data class Coffee(
val date: String,
val description: String
)
您的序列化和反序列化:
// 首先,获取SharedPreferences的字符串元素并转换为列表
var itemListString = getMyCoffeesFromPreferences()
val gson = Gson()
val itemType = object : TypeToken<List<Coffee>>() {}.type
itemList = gson.fromJson<List<Coffee>>(itemListString, itemType)
// 将新元素添加到列表中,将其转换为字符串并再次保存在SharedPreferences中
itemList.add(Coffee("08/07/2020","Test"))
val stringJSON = Gson().toJson(itemList)
saveMyCoffees(stringJSON)
我没有测试这段代码,但希望它能帮助您
英文:
If you want save a list of data in sharedpreferences you can create a list of your model and serialize and deserialize with gson to save your data in shared preferences. A fast example:
Your model:
data class Coffee(
val date: String,
val description: String
)
Your serialization and deserialization:
// First, get string element of sharedpreferences and convert to a list
var itemListString = getMyCoffeesFromPreferences()
val gson = Gson()
val itemType = object : TypeToken<List<Coffee>>() {}.type
itemList = gson.fromJson<List<Coffee>>(itemListString, itemType)
// Add new elements to list, convert it to string and save it in preferences again
itemList.add(Coffee("08/07/2020","Test"))
val stringJSON = Gson().toJson(itemList)
saveMyCoffees(stringJSON)
I have not tested the code but it can help you
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论