Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert ArrayList to string and back to ArrayList?

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]
like image 716
lisovaccaro Avatar asked Sep 05 '12 07:09

lisovaccaro


People also ask

How do you convert an ArrayList to a String in Java?

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.

Can we convert String to ArrayList?

We can easily convert String to ArrayList in Java using the split() method and regular expression.

How do I return an array from a list in Java?

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.


1 Answers

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.

like image 152
user5752479 Avatar answered Oct 12 '22 22:10

user5752479