如何在Android应用中使用SharedPreferences保存每日数据?

huangapple go评论72阅读模式
英文:

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)

我没有测试这段代码,但希望它能帮助您 如何在Android应用中使用SharedPreferences保存每日数据?

英文:

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&lt;List&lt;Coffee&gt;&gt;() {}.type
itemList = gson.fromJson&lt;List&lt;Coffee&gt;&gt;(itemListString, itemType)

// Add new elements to list, convert it to string and save it in preferences again
itemList.add(Coffee(&quot;08/07/2020&quot;,&quot;Test&quot;))
val stringJSON = Gson().toJson(itemList)
saveMyCoffees(stringJSON)

I have not tested the code but it can help you 如何在Android应用中使用SharedPreferences保存每日数据?

huangapple
  • 本文由 发表于 2020年8月7日 19:18:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63300734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定