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]
share|improve this question
feedback

4 Answers

up vote 7 down vote accepted
+50

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 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);
    
share|improve this answer
I changed the array elements to strings, I'm sure it must be a lot easier now. – Liso22 Jan 13 at 23:51
It doesn't matter. With Gson, you can convert any java object to a string and then convert it back. So even if you have an arraylist of custom objects, there's no problem. – Dhruv Gairola Jan 13 at 23:54
feedback

Build your own converter, for example:

public static String toLisoString(ArrayList<String> lisoList)
{
    if(lisoList == null) return null;

    StringBuilder sb = new StringBuilder();

    for(String s : lisoList)
    {
        if(s == null) sb.append("-1_");
        else
        {
            sb.append(s.length() + "_" + s);
        }
    }

    return sb.toString();
}
/* Take care of any runtime exception here */
public static ArrayList<String> toLisoArrayList(String lisoString) throws CorruptedLisoStringException
{
    if(lisoString == null) return null;

    ArrayList<String> lisoList = new ArrayList<String>();

    while(lisoString.length() > 0)
    {
        try
        {
            int next_ = lisoString.indexOf("_");
            int size = Integer.parseInt(lisoString.substring(0, next_));
            lisoString = lisoString.substring(next_ + 1);
            String token;
            if(size >= 0) token = lisoString.substring(0, size);
            else token = null;
            lisoString = lisoString.substring(size);
            lisoList.add(token);
         }
         catch(Exception e)
         {
             throw new CorruptedLisoStringException(e);
         }
    }

    return lisoList;
}

I didn't test it, but I hope it will work!

share|improve this answer
feedback

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.

share|improve this answer
Did you see my answer? – Eng.Fouad Jan 16 at 3:32
feedback

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.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.