Java convert ArrayList to string and back to ArrayList?
You have 2 choices :
- Manually parse the string and recreate the arraylist. This would be pretty tedious.
Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,
// How to store JSON string Gson gson = new Gson(); // This can be any object. Does not have to be an arraylist. String json = gson.toJson(myAppsArr); // How to retrieve your Java object back from the string Gson gson = new Gson(); DataObject obj = gson.fromJson(arrayString, ArrayList.class);
//arraylist convert into String using Gson
Gson gson = new Gson();
String data = gson.toJson(myArrayList);
Log.e(TAG, "json:" + gson);
//String to ArrayList
Gson gson = new Gson();
arrayList=gson.fromJson(data, new TypeToken<List<Friends>>()
{}.getType());
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.
Try this
ArrayList<String> array = Arrays.asList(arrayString.split(","))
This will work if comma is used as separator and none of the items have it.