Answer the question
In order to leave comments, you need to log in
Saving the list in shared preferences, what other ways are there?
I found such an option on the Internet, but in one of the answers I read that it is no longer recommended to use gson and json for saving, but what should I use then?
private fun saveList(mList:ArrayList<ModelList>) {
val sPref:SharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
val editor: SharedPreferences.Editor = sPref.edit()
val gson: Gson = Gson()
val json = gson.toJson(mList)
editor.putString("list",json)
editor.apply()
}
private fun getSavedListFromSP(){
val sPref: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
val gson=Gson()
val json = sPref.getString("list",null)
val type = object : TypeToken<ArrayList<ModelList>>() {}.type
val savedList = gson.fromJson<ArrayList<ModelList>>(json,type)
savedList?.let {it1->
it1.forEach {it2->
list.add(it2)
}
}
}
Answer the question
In order to leave comments, you need to log in
Nothing. SharedPreferences are not intended to store lists, and their interface clearly reflects this. It is clear that if you let the user save the lines, then you can shove anything there, but you don’t need to.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question