我已经将数组解析为JSON
并将其存储在shared preferences
中,但是如何将其从JSON取回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
现在可以将其从共享首选项取回并放入数组。
//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
}
设置数据类型似乎揭示了一个问题:
var newArray: ListArray<String> = Gson().fromJson(getArray, RecipesActivity::class.java)
说List required, found RecipesActivity
我认为我还没有完全了解该怎么做。例如,我不明白最后一个参数RecipesActivity::class.java
更新 尝试过
var newArray: ArrayList<String> = Gson().fromJson(getArray, ArrayList<String>().javaClass)
但它会崩溃并出现空点异常。