0

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.

tore
  • 619
  • 2
  • 9
  • 23
  • 1
    Documentation of method `fromJson`: https://google.github.io/gson/apidocs/com/google/gson/Gson.html#fromJson-java.lang.String-java.lang.Class-. If you want to get an object of type `T`, the last argument must be the class of `T`. In your case, you want to get a `ListArray` but you are passing `RecipesActivity::class.java`. – JavierSA Aug 09 '18 at 14:10
  • Tried changing it to `ListArray` but then it says unresolved reference... – tore Aug 09 '18 at 14:32
  • Try this: `var newArray: List = Gson().fromJson>(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. – JavierSA Aug 09 '18 at 15:48

0 Answers0