Skip to content Skip to sidebar Skip to footer

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

Solution 1:

You have 2 choices :

  1. Manually parse the string and recreate the arraylist. This would be pretty tedious.
  2. 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 stringGsongson=newGson();
    // This can be any object. Does not have to be an arraylist.Stringjson= gson.toJson(myAppsArr);
    
    // How to retrieve your Java object back from the stringGsongson=newGson();
    DataObjectobj= gson.fromJson(arrayString, ArrayList.class);
    

Solution 2:

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.

Solution 3:

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.

Solution 4:

//arraylist convert into String using Gson Gsongson=newGson();
      Stringdata= gson.toJson(myArrayList);
      Log.e(TAG, "json:" + gson);

      //String to ArrayListGsongson=newGson();
      arrayList=gson.fromJson(data, newTypeToken<List<Friends>>()
      {}.getType());

Solution 5:

I ended up using:

ArrayList<String> appList = new ArrayList<String>(Arrays.asList(appsString.split("\\s*,\\s*")));

This doesn't work for all array types though. This option differs from:

ArrayList<String> array = Arrays.asList(arrayString.split(","));

on that the second option creates an inmutable array.

Post a Comment for "Java Convert Arraylist To String And Back To Arraylist?"