0

i have ArrayList with multiple value. i want to convert this ArrayList into String to save in sharedPreferences, then I want to retrieve the String and convert it back to ArrayList

Please tell how to do that? (or any other idea to store and retrieve ArrayList)

1
  • 1
    You should at least include some code snippet of where you are stuck. Commented Jan 31, 2015 at 10:04

2 Answers 2

3

Convert arraylist to string:

String str = "";

for (String s : arraylist)
{
    str += s + ",";
}

Save string into sharedpreference:

PreferenceManager.getDefaultSharedPreferences(context).edit().putString("mystr", str).commit();

get string from sharedpreference:

String str =    PreferenceManager.getDefaultSharedPreferences(context).getString("mystr", "defaultStringIfNothingFound");

Convert string to arraylist:

List<String> arraylist = new ArrayList<String>(Arrays.asList(str.split(",")));
Sign up to request clarification or add additional context in comments.

1 Comment

Note:- This works only for Arraylist of type String, ArrayList can be of any type. The question points at ArrayList<CustomClass>
3

You can use Google's GSON.

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html

https://code.google.com/p/google-gson/

You get the idea:

  • Store: Convert Object to JSON String -> Save string
  • Retrieve: Get string -> Convert from JSON to Object

2 Comments

but gson is deprecated
click here .. when you click to download then message come

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.