Reputation: 51
I created an android app with kotlin, in this app i use a WS that provides all the list of products. So, how can i save the list of products in SharedPreferences with a moshi library? Here's my code:
fun setArrayDataBykeyValue(context: Context, key: String, DataArrayList: Array<ProductData>) {
val gson = Gson()
val jsonString = gson.toJson(DataArrayList)
val sp = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
sp.edit().putString(key, jsonString).commit()
}
Upvotes: 2
Views: 3952
Reputation: 444
I know you are asking for Moshi library, but I want provide you my Kotlin extension functions for working with ArrayList
as saved in SharedPreferences using Gson.
I think it's easy to convert this to using Moshi library and it's very useful.
inline fun <reified T> SharedPreferences.addItemToList(spListKey: String, item: T) {
val savedList = getList<T>(spListKey).toMutableList()
savedList.add(item)
val listJson = Gson().toJson(savedList)
edit { putString(spListKey, listJson) }
}
inline fun <reified T> SharedPreferences.removeItemFromList(spListKey: String, item: T) {
val savedList = getList<T>(spListKey).toMutableList()
savedList.remove(item)
val listJson = Gson().toJson(savedList)
edit {
putString(spListKey, listJson)
}
}
fun <T> SharedPreferences.putList(spListKey: String, list: List<T>) {
val listJson = Gson().toJson(list)
edit {
putString(spListKey, listJson)
}
}
inline fun <reified T> SharedPreferences.getList(spListKey: String): List<T> {
val listJson = getString(spListKey, "")
if (!listJson.isNullOrBlank()) {
val type = object : TypeToken<List<T>>() {}.type
return Gson().fromJson(listJson, type)
}
return listOf()
}
Upvotes: 2
Reputation: 160
You can use GSON library for this.
At first, you have to convert the ArrayList to string. For example:
val arrayString = Gson().toJson(arrayList)
Then, you can store the string in SharedPreference. To retrieve the String, you have to retrieve the String first and then convert it again to ArrayList. For example:
val collectionType = object : TypeToken<ArrayList<String>>() {}.type
arrayList = Gson().fromJson(arrayString, collectionType)
Let me know if you face any problem in this regard.
Upvotes: 0
Reputation: 11018
Here is how you can do it.
Moshi moshi = new Moshi.Builder().build();
Type type = Types.newParameterizedType(List.class, Person.class);
JsonAdapter< List > jsonAdapter = moshi.adapter(type);
String json = jsonAdapter.toJson(body.getParams());
where Person is your POJO or some model class.
and then save this string in shared preference and do the reverse like this to get back in List
List<Person> persons = jsonAdapter.fromJson(json);
Upvotes: 3