I have parsed an array to JSON
and stored it in shared preferences
but how do I get it back from JSON to an array
?
var savedFavRecipes: ArrayList<String>? = null
var sp = context.getSharedPreferences("FAV", Context.MODE_PRIVATE)
savedFavRecipes?.add(recipeArray!![counterX!!].recipeKey!!) //Stores a string in an array
var myJSON = Gson().toJson(savedFavRecipes) //parse the array to JSON
var spStorage = sp.edit()
spStorage.putString("KEY", myJSON).apply() //Store in Shared preference
Now to retrieve it back from shared preference and into an array.
//GET FROM SHARED PREFERENCE PARCED FROM JSON
var getArray = sp.getString("KEY", null)
if(getArray != null) {
var newArray = Gson().fromJson(getArray, RecipesActivity::class.java)
Log.d("TAG", " " + newArray[0]) //Crashes
}
Setting datatype seems to reveal a problem:
var newArray: ListArray<String> = Gson().fromJson(getArray, RecipesActivity::class.java)
Says List required, found RecipesActivity
Think I don't fully get how to do this. For example, I don't understand the point of the last argument RecipesActivity::class.java
UPDATE Tried
var newArray: ArrayList<String> = Gson().fromJson(getArray, ArrayList<String>().javaClass)
but it crashes with a null point exception.
>(getArray, object : TypeToken
>() {}.type)`. Info from https://stackoverflow.com/a/33381385/1861769. And I suggest creating the `inline fun` that is shown in the answer.