I wanted to save an ArrayList to SharedPreferences so I need to turn it into a string and back, this is what I am doing:
// Save to shared preferences
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("myAppsArr", myAppsArr.toString());
editor.commit();
I can retrieve it with String arrayString = sharedPref.getString("yourKey", null);
but I don't know how to convert arrayString back into an ArrayList. How can it be done?
My array looks something like:
[item1,item2,item3]
To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.
We can easily convert String to ArrayList in Java using the split() method and regular expression.
By using the toArray() method, we can easily convert a list into an array. The toArray() method returns an array having all the elements in the list. The returned array contains elements in the same sequence as the list.
The page http://mjiayou.com/2015/07/22/exception-gson-internal-cannot-be-cast-to/ contains the following:
Type type = new TypeToken<List<T>>(){}.getType();
List<T> list = gson.fromJson(jsonString, type)
perhaps it will be helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With