0

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)

iatharva
  • 79
  • 2
  • 9
  • see this https://stackoverflow.com/a/63300609/8719734 , create a seperate class create methods of what you want to store and get – aryanknp Aug 07 '20 at 11:21

1 Answers1

1

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 :-|

Yeray
  • 1,265
  • 1
  • 11
  • 23