Save ArrayList to SharedPreferences
Asked Answered
B

38

376

I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don't need the array available after the application has been closed completely. I save a lot of other objects this way by using the SharedPreferences but I can't figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences isn't the way to go about this? Is there a simpler method?

Brennen answered 14/8, 2011 at 15:46 Comment(3)
You can find Answer here : #14981733Thirteenth
this is the complete example go through the url https://mcmap.net/q/88304/-how-to-setup-alertbox-from-broadcastreceiverEndoscope
If anyone is looking for the solution, this might be the answer you are seeking with full usage example in kotlin. https://mcmap.net/q/88305/-kotlin-sharedpreferences-save-listview-items-and-load-themTravis
T
474

After API 11 the SharedPreferences Editor accepts Sets. You could convert your List into a HashSet or something similar and store it like that. When you read it back, convert it into an ArrayList, sort it if needed and you're good to go.

//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);

//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();

You can also serialize your ArrayList and then save/read it to/from SharedPreferences. Below is the solution:

EDIT:
Ok, below is the solution to save ArrayList as a serialized object to SharedPreferences and then read it from SharedPreferences.

Because API supports only storing and retrieving of strings to/from SharedPreferences (after API 11, it's simpler), we have to serialize and de-serialize the ArrayList object which has the list of tasks into a string.

In the addTask() method of the TaskManagerApplication class, we have to get the instance of the shared preference and then store the serialized ArrayList using the putString() method:

public void addTask(Task t) {
  if (null == currentTasks) {
    currentTasks = new ArrayList<task>();
  }
  currentTasks.add(t);
 
  // save the task list to preference
  SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
  Editor editor = prefs.edit();
  try {
    editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
  } catch (IOException e) {
    e.printStackTrace();
  }
  editor.commit();
}

Similarly we have to retrieve the list of tasks from the preference in the onCreate() method:

public void onCreate() {
  super.onCreate();
  if (null == currentTasks) {
    currentTasks = new ArrayList<task>();
  }
 
  // load tasks from preference
  SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
 
  try {
    currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
  } catch (IOException e) {
    e.printStackTrace();
  } catch (ClassNotFoundException e) {
    e.printStackTrace();
  }
}

You can get the ObjectSerializer class from the Apache Pig project ObjectSerializer.java

Terpsichore answered 14/8, 2011 at 15:49 Comment(14)
Keep in mind that putStringSet was added at API 11. Most current programmers target at lease API 8 (Froyo).Humblebee
I like the idea of this method because it seems to be the cleanest, but the array I am looking to store is a custom class object that contains strings, doubles, and booleans. How do I go about adding all 3 of these types to a set? Do I have to set every individual object to their own array and then add them individually to separate sets before I store, or is there a simpler way?Brennen
Like Christian said, this feature was added at API 11 and I don't recommend you to use this, because API 11 is used by very small group of devices. Look for my EDIT section - there's a suggestion for an earlier API versions.Terpsichore
@Humblebee would that be said "at least API 8" or "at most API 8" ... or "use API 8 as their minimum requirements"? Gar I'm confused now.Aussie
Second solution works, but I got error "cant cast ArrayList to Set" when trying the first solution.Millur
@Terpsichore how can i save custom objects using the above method i m not dealing with stringIncentive
@ErumHannan You could use for example Gson object and serialize your custom object to json string. Then you'll save it to the shared preferences as in my example.Terpsichore
Can we add a ArrayList of custom objects to shared preference? This solution only seems for a ArrayList of String type.Buffum
What is scoreEditor?Cantlon
You can also use Google's Gson.Volscian
To readers after Oct-2016: This comment already gets a lot of upvote and you may use it like me, but please halt and don't do this. HashSet will discard duplicate value, thus your ArrayList won't be same. Details here: #12941163Later
task must be serializableTaneshatang
As a reminder to those coming across this answer: a Set is unordered, so saving a StringSet will lose the order you had with your ArrayList.Cryogenics
I got error. java.lang.ArrayIndexOutOfBoundsException: length=107; index=107. when task deserializePatroclus
B
134

Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple.

TinyDB tinydb = new TinyDB(context);

to put

tinydb.putList("MyUsers", mUsersArray);

to get

tinydb.getList("MyUsers");

UPDATE

Some useful examples and troubleshooting might be found here: Android Shared Preference TinyDB putListObject frunction

Boletus answered 21/4, 2014 at 1:31 Comment(13)
depending on the content of your List, you have to specify the object type of your list when calling tinydb.putList() Look at the examples at the linked page.Boletus
good lib, but i should mention that sometimes this library has issues when storing objects. to be more specific, it may throw stack overflow exception. and i think it is because it uses reflection to figure out how to store the object, and if the object gets too complicated it may throw that exception.Dorr
What should i set as context parameter on TinyDB tinydb = new TinyDB(context); ?Nonchalant
@AndreasKonstantakos getApplicationContext() that is new TinyDB(getApplicationContext());Boletus
Currently, putList() became putListString()Timbrel
@xscoder there was never a putList() function. I said putList() in the example to keep things simple, because there are many other functions that start from the phrase putList in TInyDB. Example putListString(), putListInt(), and many others.Boletus
How can I set default value to getList()?Externality
@RAWNAKYAZDANI by default, TinyDB will return an empty list for a value that doesn't exist, so check the size of the list returned; if it is 0, then you can assign what ever default value you want to the returned list variable.Boletus
Don't use this! Especially not the getListString() and setListString() Why? It uses a magic separator pattern ‚‗‚ to separate string items and stores them in a plain String. The problem with this is that if your string ever contains this magic pattern it will break the implementation. A possible fix to avoid it from breaking would be to escape input strings (and do the reverse while reading). Another option which is easier to implement but less efficient, is to first transform the input strings to a format which is guaranteed to never have the magic pattern, such as Base64.Nap
@Rolfツ lets be real here; what are the chances of a user accidentally entering ‚‗‚ as an input? Zero to be honest because those are rarely used unicode characters, and they are not bundled in any mainstream keyboard that I know of. Even if one of them is bundled, the user has to enter them in that exact order with the other rare unicode character. I had your fears in mind eight years ago when I created this library, that is why I used rare keys (unicodes) as list separators.Boletus
@kcochibili it totally depends on your use-case? What if someone uses your library to store a string created from a random byte array? Basically to be able to store binary data? Suddenly it is not so rare anymore. Yes this may work for many developers, but it is not waterproof and it is a bug waiting to happen.Nap
@Rolfツ Based on your argument, what do you have to say about JSON, which structures its data (including lists) using everyday characters like commas and parenthesis; The whole world uses JSON. What do you have to say about that? At least tinydb tries to make it hard for things to break.Boletus
@kcochibili JSON is extremely safe as it is able to carry anything, including your magic separator pattern. How is JSON doing that? They escape characters that are part of the syntax. In strings (that can contain any character) they do this by using an escape sequence (double quotes are escaped). You can read more about that in the specification: ecma-international.org/publications-and-standards/standards/…. This makes it possible for JSON to store any byte in any combination, without the need for magic separator patterns.Nap
C
95

Saving Array in SharedPreferences:

public static boolean saveArray()
{
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor mEdit1 = sp.edit();
    /* sKey is an array */
    mEdit1.putInt("Status_size", sKey.size());  

    for(int i=0;i<sKey.size();i++)  
    {
        mEdit1.remove("Status_" + i);
        mEdit1.putString("Status_" + i, sKey.get(i));  
    }

    return mEdit1.commit();     
}

Loading Array Data from SharedPreferences

public static void loadArray(Context mContext)
{  
    SharedPreferences mSharedPreference1 =   PreferenceManager.getDefaultSharedPreferences(mContext);
    sKey.clear();
    int size = mSharedPreference1.getInt("Status_size", 0);  

    for(int i=0;i<size;i++) 
    {
     sKey.add(mSharedPreference1.getString("Status_" + i, null));
    }

}
Clypeate answered 15/6, 2012 at 12:42 Comment(4)
this is a very nice "hack". Be aware that with this method, there is always the posibility of bloating the SharedPreferences with unused old values. For example a list might have a size of 100 on a run, and then a size of 50. The 50 old entries will remain on the preferences. One way is setting a MAX value and clearing anything up to that.Hymie
@Hymie Indeed, but assuming that you store only this ArrayList into SharedPrefeneces you could use mEdit1.clear() to avoid this.Jurisprudent
I like this "hack". But mEdit1.clear() will erase other values not relevant to this purpose?Ensemble
Thanks! If you mind me asking, is there a necessary purpose for .remove()? Won't the preference just overwrite anyway?Muldrow
C
76

As @nirav said, best solution is store it in sharedPrefernces as a json text by using Gson utility class. Below sample code:

//Retrieve the values
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson


//Set the values
Gson gson = new Gson();
List<String> textList = new ArrayList<String>(data);
String jsonText = gson.toJson(textList);
prefsEditor.putString("key", jsonText);
prefsEditor.apply();
Chemoreceptor answered 10/1, 2015 at 2:33 Comment(3)
This answer shoud be way up. Superb! Had no idea I can use Gson this way. First time to see the array notation used this way too. Thank you!Defibrillator
To convert it back to List, List<String> textList = Arrays.asList(gson.fromJson(jsonText, String[].class));Custodial
What is "data"?Menorrhagia
C
70

You can convert it to JSON String and store the string in the SharedPreferences.

Cockscomb answered 14/8, 2011 at 15:47 Comment(5)
I'm finding a ton of code on converting ArrayLists to JSONArrays, but do you have a sample you might be willing to share on how to convert over to JSONString so I can store it in the SharedPrefs?Brennen
using toString()Cockscomb
But then how do I get it back out of SharedPrefs and convert it back into an ArrayList?Brennen
I'm sorry, I don't have an Android SDK to test it now, but take a look here: benjii.me/2010/04/deserializing-json-in-android-using-gson . You should iterate over the json array and do what they do there for each object, hopefully I'll be able to post an edit to my answer with a full example tomorrow.Cockscomb
@Cockscomb 12 years later...Discomposure
S
69
/**
 *     Save and get ArrayList in SharedPreference
 */

JAVA:

public void saveArrayList(ArrayList<String> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply();    

}

public ArrayList<String> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);
}

Kotlin

fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
    val editor: Editor = prefs.edit()
    val gson = Gson()
    val json: String = gson.toJson(list)
    editor.putString(key, json)
    editor.apply()
}

fun getArrayList(key: String?): java.util.ArrayList<String?>? {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
    val gson = Gson()
    val json: String = prefs.getString(key, null)
    val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()
    return gson.fromJson(json, type)
}
Shovel answered 20/6, 2019 at 9:21 Comment(4)
can you make this that means it will store all model class ?Matty
Yes i tried it , perfect for storing data to sharedprefs! i voted up.Cakewalk
What is Type import?Moralist
show lots of option for importing the Type which is inside the getArrayList methodGraybill
N
23

Hey friends I got the solution of above problem without using Gson library. Here I post source code.

1.Variable declaration i.e

  SharedPreferences shared;
  ArrayList<String> arrPackage;

2.Variable initialization i.e

 shared = getSharedPreferences("App_settings", MODE_PRIVATE);
 // add values for your ArrayList any where...
 arrPackage = new ArrayList<>();

3.Store value to sharedPreference using packagesharedPreferences():

 private void packagesharedPreferences() {
   SharedPreferences.Editor editor = shared.edit();
   Set<String> set = new HashSet<String>();
   set.addAll(arrPackage);
   editor.putStringSet("DATE_LIST", set);
   editor.apply();
   Log.d("storesharedPreferences",""+set);
 }

4.Retrive value of sharedPreference using retriveSharedValue():

 private void retriveSharedValue() {
   Set<String> set = shared.getStringSet("DATE_LIST", null);
   arrPackage.addAll(set);
   Log.d("retrivesharedPreferences",""+set);
 }

I hope it will helpful for you...

Nellie answered 26/4, 2016 at 19:58 Comment(3)
This would remove all duplicate strings from the list as soon as you add to a set. Probably not a wanted featurePrajna
Is it only for a list of Strings?Tew
You will lose order this wayLubricity
P
15

Android SharedPreferances allow you to save primitive types (Boolean, Float, Int, Long, String and StringSet which available since API11) in memory as an xml file.

The key idea of any solution would be to convert the data to one of those primitive types.

I personally love to convert the my list to json format and then save it as a String in a SharedPreferences value.

In order to use my solution you'll have to add Google Gson lib.

In gradle just add the following dependency (please use google's latest version):

compile 'com.google.code.gson:gson:2.6.2'

Save data (where HttpParam is your object):

List<HttpParam> httpParamList = "**get your list**"
String httpParamJSONList = new Gson().toJson(httpParamList);

SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(**"your_prefes_key"**, httpParamJSONList);

editor.apply();

Retrieve Data (where HttpParam is your object):

SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
String httpParamJSONList = prefs.getString(**"your_prefes_key"**, ""); 

List<HttpParam> httpParamList =  
new Gson().fromJson(httpParamJSONList, new TypeToken<List<HttpParam>>() {
            }.getType());
Punchinello answered 23/3, 2016 at 17:3 Comment(0)
R
12

This is your perfect solution.. try it,

public void saveArrayList(ArrayList<String> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply();     // This line is IMPORTANT !!!
}

public ArrayList<String> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);
}
Rosenblum answered 4/12, 2018 at 6:2 Comment(0)
E
10

You can also convert the arraylist into a String and save that in preference

private String convertToString(ArrayList<String> list) {

            StringBuilder sb = new StringBuilder();
            String delim = "";
            for (String s : list)
            {
                sb.append(delim);
                sb.append(s);;
                delim = ",";
            }
            return sb.toString();
        }

private ArrayList<String> convertToArray(String string) {

            ArrayList<String> list = new ArrayList<String>(Arrays.asList(string.split(",")));
            return list;
        }

You can save the Arraylist after converting it to string using convertToString method and retrieve the string and convert it to array using convertToArray

After API 11 you can save set directly to SharedPreferences though !!! :)

Equitation answered 5/9, 2014 at 7:7 Comment(1)
A set is not a list. A list could contain duplicates and can be sorted. It doesn't make sense to set the delimiter in the loop. Should be a constant/define. Does it even work like this if the delimiter is contained in the string?Myrlemyrlene
T
9

Also with Kotlin:

fun SharedPreferences.Editor.putIntegerArrayList(key: String, list: ArrayList<Int>?): SharedPreferences.Editor {
    putString(key, list?.joinToString(",") ?: "")
    return this
}

fun SharedPreferences.getIntegerArrayList(key: String, defValue: ArrayList<Int>?): ArrayList<Int>? {
    val value = getString(key, null)
    if (value.isNullOrBlank())
        return defValue
    return ArrayList (value.split(",").map { it.toInt() }) 
}
Tanner answered 23/5, 2018 at 6:35 Comment(0)
N
9

For String, int, boolean, the best choice would be sharedPreferences.

If you want to store ArrayList or any complex data. The best choice would be Paper library.

Add dependency

implementation 'io.paperdb:paperdb:2.6'

Initialize Paper

Should be initialized once in Application.onCreate():

Paper.init(context);

Save

List<Person> contacts = ...
Paper.book().write("contacts", contacts);

Loading Data

Use default values if object doesn't exist in the storage.

List<Person> contacts = Paper.book().read("contacts", new ArrayList<>());

Here you go.

https://github.com/pilgr/Paper

Nephritic answered 11/9, 2019 at 12:28 Comment(0)
W
7

You can save String and custom array list using Gson library.

=>First you need to create function to save array list to SharedPreferences.

public void saveListInLocal(ArrayList<String> list, String key) {

        SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString(key, json);
        editor.apply();     // This line is IMPORTANT !!!

    }

=> You need to create function to get array list from SharedPreferences.

public ArrayList<String> getListFromLocal(String key)
{
    SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);

}

=> How to call save and retrieve array list function.

ArrayList<String> listSave=new ArrayList<>();
listSave.add("test1"));
listSave.add("test2"));
saveListInLocal(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<String> listGet=new ArrayList<>();
listGet=getListFromLocal("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());

=> Don't forgot to add gson library in you app level build.gradle.

implementation 'com.google.code.gson:gson:2.8.2'

Waiwaif answered 19/4, 2018 at 9:35 Comment(0)
R
6

best way is that convert to JSOn string using GSON and save this string to SharedPreference. I also use this way to cache responses.

Rhinitis answered 21/3, 2013 at 0:10 Comment(0)
O
5

I have read all answers above. That is all correct but i found a more easy solution as below:

  1. Saving String List in shared-preference>>

    public static void setSharedPreferenceStringList(Context pContext, String pKey, List<String> pData) {
    SharedPreferences.Editor editor = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit();
    editor.putInt(pKey + "size", pData.size());
    editor.commit();
    
    for (int i = 0; i < pData.size(); i++) {
        SharedPreferences.Editor editor1 = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit();
        editor1.putString(pKey + i, (pData.get(i)));
        editor1.commit();
    }
    

    }

  2. and for getting String List from Shared-preference>>

    public static List<String> getSharedPreferenceStringList(Context pContext, String pKey) {
    int size = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getInt(pKey + "size", 0);
    List<String> list = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        list.add(pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getString(pKey + i, ""));
    }
    return list;
    }
    

Here Constants.APP_PREFS is the name of the file to open; can not contain path separators.

Oto answered 30/12, 2016 at 11:37 Comment(0)
C
4

Using Kotlin and GSON:

fun <T> SharedPreferences.writeList(gson: Gson, key: String, data: List<T>) {
    val json = gson.toJson(data)
    edit { putString(key, json) }
}

inline fun <reified T> SharedPreferences.readList(gson: Gson, key: String): List<T> {
    val json = getString(key, "[]") ?: "[]"
    val type = object : TypeToken<List<T>>() {}.type
    
    return try {
        gson.fromJson(json, type)
    } catch(e: JsonSyntaxException) {
        emptyList()
    }
}
Cardialgia answered 6/7, 2022 at 7:35 Comment(0)
T
3

You could refer the serializeKey() and deserializeKey() functions from FacebookSDK's SharedPreferencesTokenCache class. It converts the supportedType into the JSON object and store the JSON string into SharedPreferences. You could download SDK from here

private void serializeKey(String key, Bundle bundle, SharedPreferences.Editor editor)
    throws JSONException {
    Object value = bundle.get(key);
    if (value == null) {
        // Cannot serialize null values.
        return;
    }

    String supportedType = null;
    JSONArray jsonArray = null;
    JSONObject json = new JSONObject();

    if (value instanceof Byte) {
        supportedType = TYPE_BYTE;
        json.put(JSON_VALUE, ((Byte)value).intValue());
    } else if (value instanceof Short) {
        supportedType = TYPE_SHORT;
        json.put(JSON_VALUE, ((Short)value).intValue());
    } else if (value instanceof Integer) {
        supportedType = TYPE_INTEGER;
        json.put(JSON_VALUE, ((Integer)value).intValue());
    } else if (value instanceof Long) {
        supportedType = TYPE_LONG;
        json.put(JSON_VALUE, ((Long)value).longValue());
    } else if (value instanceof Float) {
        supportedType = TYPE_FLOAT;
        json.put(JSON_VALUE, ((Float)value).doubleValue());
    } else if (value instanceof Double) {
        supportedType = TYPE_DOUBLE;
        json.put(JSON_VALUE, ((Double)value).doubleValue());
    } else if (value instanceof Boolean) {
        supportedType = TYPE_BOOLEAN;
        json.put(JSON_VALUE, ((Boolean)value).booleanValue());
    } else if (value instanceof Character) {
        supportedType = TYPE_CHAR;
        json.put(JSON_VALUE, value.toString());
    } else if (value instanceof String) {
        supportedType = TYPE_STRING;
        json.put(JSON_VALUE, (String)value);
    } else {
        // Optimistically create a JSONArray. If not an array type, we can null
        // it out later
        jsonArray = new JSONArray();
        if (value instanceof byte[]) {
            supportedType = TYPE_BYTE_ARRAY;
            for (byte v : (byte[])value) {
                jsonArray.put((int)v);
            }
        } else if (value instanceof short[]) {
            supportedType = TYPE_SHORT_ARRAY;
            for (short v : (short[])value) {
                jsonArray.put((int)v);
            }
        } else if (value instanceof int[]) {
            supportedType = TYPE_INTEGER_ARRAY;
            for (int v : (int[])value) {
                jsonArray.put(v);
            }
        } else if (value instanceof long[]) {
            supportedType = TYPE_LONG_ARRAY;
            for (long v : (long[])value) {
                jsonArray.put(v);
            }
        } else if (value instanceof float[]) {
            supportedType = TYPE_FLOAT_ARRAY;
            for (float v : (float[])value) {
                jsonArray.put((double)v);
            }
        } else if (value instanceof double[]) {
            supportedType = TYPE_DOUBLE_ARRAY;
            for (double v : (double[])value) {
                jsonArray.put(v);
            }
        } else if (value instanceof boolean[]) {
            supportedType = TYPE_BOOLEAN_ARRAY;
            for (boolean v : (boolean[])value) {
                jsonArray.put(v);
            }
        } else if (value instanceof char[]) {
            supportedType = TYPE_CHAR_ARRAY;
            for (char v : (char[])value) {
                jsonArray.put(String.valueOf(v));
            }
        } else if (value instanceof List<?>) {
            supportedType = TYPE_STRING_LIST;
            @SuppressWarnings("unchecked")
            List<String> stringList = (List<String>)value;
            for (String v : stringList) {
                jsonArray.put((v == null) ? JSONObject.NULL : v);
            }
        } else {
            // Unsupported type. Clear out the array as a precaution even though
            // it is redundant with the null supportedType.
            jsonArray = null;
        }
    }

    if (supportedType != null) {
        json.put(JSON_VALUE_TYPE, supportedType);
        if (jsonArray != null) {
            // If we have an array, it has already been converted to JSON. So use
            // that instead.
            json.putOpt(JSON_VALUE, jsonArray);
        }

        String jsonString = json.toString();
        editor.putString(key, jsonString);
    }
}

private void deserializeKey(String key, Bundle bundle)
        throws JSONException {
    String jsonString = cache.getString(key, "{}");
    JSONObject json = new JSONObject(jsonString);

    String valueType = json.getString(JSON_VALUE_TYPE);

    if (valueType.equals(TYPE_BOOLEAN)) {
        bundle.putBoolean(key, json.getBoolean(JSON_VALUE));
    } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        boolean[] array = new boolean[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getBoolean(i);
        }
        bundle.putBooleanArray(key, array);
    } else if (valueType.equals(TYPE_BYTE)) {
        bundle.putByte(key, (byte)json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_BYTE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        byte[] array = new byte[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (byte)jsonArray.getInt(i);
        }
        bundle.putByteArray(key, array);
    } else if (valueType.equals(TYPE_SHORT)) {
        bundle.putShort(key, (short)json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_SHORT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        short[] array = new short[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (short)jsonArray.getInt(i);
        }
        bundle.putShortArray(key, array);
    } else if (valueType.equals(TYPE_INTEGER)) {
        bundle.putInt(key, json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int[] array = new int[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getInt(i);
        }
        bundle.putIntArray(key, array);
    } else if (valueType.equals(TYPE_LONG)) {
        bundle.putLong(key, json.getLong(JSON_VALUE));
    } else if (valueType.equals(TYPE_LONG_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        long[] array = new long[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getLong(i);
        }
        bundle.putLongArray(key, array);
    } else if (valueType.equals(TYPE_FLOAT)) {
        bundle.putFloat(key, (float)json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        float[] array = new float[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (float)jsonArray.getDouble(i);
        }
        bundle.putFloatArray(key, array);
    } else if (valueType.equals(TYPE_DOUBLE)) {
        bundle.putDouble(key, json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        double[] array = new double[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getDouble(i);
        }
        bundle.putDoubleArray(key, array);
    } else if (valueType.equals(TYPE_CHAR)) {
        String charString = json.getString(JSON_VALUE);
        if (charString != null && charString.length() == 1) {
            bundle.putChar(key, charString.charAt(0));
        }
    } else if (valueType.equals(TYPE_CHAR_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        char[] array = new char[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            String charString = jsonArray.getString(i);
            if (charString != null && charString.length() == 1) {
                array[i] = charString.charAt(0);
            }
        }
        bundle.putCharArray(key, array);
    } else if (valueType.equals(TYPE_STRING)) {
        bundle.putString(key, json.getString(JSON_VALUE));
    } else if (valueType.equals(TYPE_STRING_LIST)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int numStrings = jsonArray.length();
        ArrayList<String> stringList = new ArrayList<String>(numStrings);
        for (int i = 0; i < numStrings; i++) {
            Object jsonStringValue = jsonArray.get(i);
            stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String)jsonStringValue);
        }
        bundle.putStringArrayList(key, stringList);
    }
}
Toughie answered 22/11, 2012 at 7:40 Comment(0)
I
3

My utils class for save list to SharedPreferences

public class SharedPrefApi {
    private SharedPreferences sharedPreferences;
    private Gson gson;

    public SharedPrefApi(Context context, Gson gson) {
        this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        this.gson = gson;
    } 

    ...

    public <T> void putList(String key, List<T> list) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, gson.toJson(list));
        editor.apply();
    }

    public <T> List<T> getList(String key, Class<T> clazz) {
        Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
        return gson.fromJson(getString(key, null), typeOfT);
    }
}

Using

// for save
sharedPrefApi.putList(SharedPrefApi.Key.USER_LIST, userList);

// for retrieve
List<User> userList = sharedPrefApi.getList(SharedPrefApi.Key.USER_LIST, User.class);

.
Full code of my utils // check using example in Activity code

Irfan answered 21/8, 2018 at 9:15 Comment(0)
F
2

Why don't you stick your arraylist on an Application class? It only get's destroyed when the app is really killed, so, it will stick around for as long as the app is available.

Feu answered 14/8, 2011 at 19:53 Comment(1)
What if the application is relaunched again.Cupp
K
2

The best way i have been able to find is a make a 2D Array of keys and put the custom items of the array in the 2-D array of keys and then retrieve it through the 2D arra on startup. I did not like the idea of using string set because most of the android users are still on Gingerbread and using string set requires honeycomb.

Sample Code: here ditor is the shared pref editor and rowitem is my custom object.

editor.putString(genrealfeedkey[j][1], Rowitemslist.get(j).getname());
        editor.putString(genrealfeedkey[j][2], Rowitemslist.get(j).getdescription());
        editor.putString(genrealfeedkey[j][3], Rowitemslist.get(j).getlink());
        editor.putString(genrealfeedkey[j][4], Rowitemslist.get(j).getid());
        editor.putString(genrealfeedkey[j][5], Rowitemslist.get(j).getmessage());
Katherinkatherina answered 6/4, 2013 at 14:26 Comment(0)
R
2

following code is the accepted answer, with a few more lines for new folks (me), eg. shows how to convert the set type object back to arrayList, and additional guidance on what goes before '.putStringSet' and '.getStringSet'. (thank you evilone)

// shared preferences
   private SharedPreferences preferences;
   private SharedPreferences.Editor nsuserdefaults;

// setup persistent data
        preferences = this.getSharedPreferences("MyPreferences", MainActivity.MODE_PRIVATE);
        nsuserdefaults = preferences.edit();

        arrayOfMemberUrlsUserIsFollowing = new ArrayList<String>();
        //Retrieve followers from sharedPreferences
        Set<String> set = preferences.getStringSet("following", null);

        if (set == null) {
            // lazy instantiate array
            arrayOfMemberUrlsUserIsFollowing = new ArrayList<String>();
        } else {
            // there is data from previous run
            arrayOfMemberUrlsUserIsFollowing = new ArrayList<>(set);
        }

// convert arraylist to set, and save arrayOfMemberUrlsUserIsFollowing to nsuserdefaults
                Set<String> set = new HashSet<String>();
                set.addAll(arrayOfMemberUrlsUserIsFollowing);
                nsuserdefaults.putStringSet("following", set);
                nsuserdefaults.commit();
Rosetterosewall answered 14/3, 2015 at 7:14 Comment(0)
L
2
//Set the values
intent.putParcelableArrayListExtra("key",collection);

//Retrieve the values
ArrayList<OnlineMember> onlineMembers = data.getParcelableArrayListExtra("key");
Literature answered 1/10, 2015 at 10:13 Comment(0)
A
2

You can use serialization or Gson library to convert list to string and vice versa and then save string in preferences.

Using google's Gson library:

//Converting list to string
new Gson().toJson(list);

//Converting string to list
new Gson().fromJson(listString, CustomObjectsList.class);

Using Java serialization:

//Converting list to string
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
oos.flush();
String string = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
oos.close();
bos.close();
return string;

//Converting string to list
byte[] bytesArray = Base64.decode(familiarVisitsString, Base64.DEFAULT);
ByteArrayInputStream bis = new ByteArrayInputStream(bytesArray);
ObjectInputStream ois = new ObjectInputStream(bis);
Object clone = ois.readObject();
ois.close();
bis.close();
return (CustomObjectsList) clone;
Accession answered 30/8, 2016 at 10:3 Comment(0)
B
2

Use this custom class:

public class SharedPreferencesUtil {

    public static void pushStringList(SharedPreferences sharedPref, 
                                      List<String> list, String uniqueListName) {

        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(uniqueListName + "_size", list.size());

        for (int i = 0; i < list.size(); i++) {
            editor.remove(uniqueListName + i);
            editor.putString(uniqueListName + i, list.get(i));
        }
        editor.apply();
    }

    public static List<String> pullStringList(SharedPreferences sharedPref, 
                                              String uniqueListName) {

        List<String> result = new ArrayList<>();
        int size = sharedPref.getInt(uniqueListName + "_size", 0);

        for (int i = 0; i < size; i++) {
            result.add(sharedPref.getString(uniqueListName + i, null));
        }
        return result;
    }
}

How to use:

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferencesUtil.pushStringList(sharedPref, list, getString(R.string.list_name));
List<String> list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));
Biysk answered 7/11, 2017 at 10:17 Comment(1)
I tried several of the solutions posted, but this was the best by far. It does not require GSON, a special library, converting to something like a Map or SDK 29. I needed to store a custom class of three members and this was easy to modify to fit. This should be voted higher. Thanks, @Yuliia.Goosefish
G
2

I used the same manner of saving and retrieving a String but here with arrayList I've used HashSet as a mediator

To save arrayList to SharedPreferences we use HashSet:

1- we create SharedPreferences variable (in place where the change happens to the array)

2 - we convert the arrayList to HashSet

3 - then we put the stringSet and apply

4 - you getStringSet within HashSet and recreate ArrayList to set the HashSet.

public class MainActivity extends AppCompatActivity {
    ArrayList<String> arrayList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences prefs = this.getSharedPreferences("com.example.nec.myapplication", Context.MODE_PRIVATE);

        HashSet<String> set = new HashSet(arrayList);
        prefs.edit().putStringSet("names", set).apply();


        set = (HashSet<String>) prefs.getStringSet("names", null);
        arrayList = new ArrayList(set);

        Log.i("array list", arrayList.toString());
    }
}
Grosbeak answered 29/5, 2018 at 17:41 Comment(0)
T
2

This method is used to store/save array list:-

 public static void saveSharedPreferencesLogList(Context context, List<String> collageList) {
            SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
            SharedPreferences.Editor prefsEditor = mPrefs.edit();
            Gson gson = new Gson();
            String json = gson.toJson(collageList);
            prefsEditor.putString("myJson", json);
            prefsEditor.commit();
        }

This method is used to retrieve array list:-

public static List<String> loadSharedPreferencesLogList(Context context) {
        List<String> savedCollage = new ArrayList<String>();
        SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
        Gson gson = new Gson();
        String json = mPrefs.getString("myJson", "");
        if (json.isEmpty()) {
            savedCollage = new ArrayList<String>();
        } else {
            Type type = new TypeToken<List<String>>() {
            }.getType();
            savedCollage = gson.fromJson(json, type);
        }

        return savedCollage;
    }
Trichoid answered 29/6, 2018 at 6:36 Comment(0)
A
1

You can convert it to a Map Object to store it, then change the values back to an ArrayList when you retrieve the SharedPreferences.

Asparagine answered 14/8, 2011 at 15:52 Comment(0)
T
1

don't forget to implement Serializable:

Class dataBean implements Serializable{
 public String name;
}
ArrayList<dataBean> dataBeanArrayList = new ArrayList();

https://mcmap.net/q/88308/-how-to-serialize-arraylist-on-android

Thule answered 5/10, 2015 at 11:54 Comment(0)
T
1

this should work:

public void setSections (Context c,  List<Section> sectionList){
    this.sectionList = sectionList;

    Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
    String sectionListString = new Gson().toJson(sectionList,sectionListType);

    SharedPreferences.Editor editor = getSharedPreferences(c).edit().putString(PREFS_KEY_SECTIONS, sectionListString);
    editor.apply();
}

them, to catch it just:

public List<Section> getSections(Context c){

    if(this.sectionList == null){
        String sSections = getSharedPreferences(c).getString(PREFS_KEY_SECTIONS, null);

        if(sSections == null){
            return new ArrayList<>();
        }

        Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
        try {

            this.sectionList = new Gson().fromJson(sSections, sectionListType);

            if(this.sectionList == null){
                return new ArrayList<>();
            }
        }catch (JsonSyntaxException ex){

            return new ArrayList<>();

        }catch (JsonParseException exc){

            return new ArrayList<>();
        }
    }
    return this.sectionList;
}

it works for me.

Tenishatenn answered 26/7, 2018 at 7:59 Comment(0)
W
1

In case someone needs to save a list of lists, i.e. List<List < String > >. I did this:

To serialize

Gson gson = new Gson();
// Save the size of the array
sharedPreferencesEditor.putInt("ArraySize", myArray.size());

for (int i=0; i<myArray.size(); i++) {
  String key = "Array"+i;
  String json = gson.toJson(myArray.get(i));
  sharedPreferencesEditor.putString(key, json);
}

sharedPreferencesEditor.commit();

To Deserialize

// Get the size of the array to be deserialized. In my case, the default number should be 3
int arraySize = sharedPreferences.getInt("ArraySize",3);

myArray = new ArrayList<List<String>>();

for (int i=0; i<arraySize; i++) {
  String key = "Array"+i;
  String json = sharedPreferences.getString(key, null);
  List<String> arrayTemp= gson.fromJson(json, List.class);
  myArray.add(arrayTemp);
}

// My array may also include components with empty strings. 
// Gson makes them null values and it is not possible 
// to deserialize them as empty strings. 
// The following takes care of that:

for (int i=0; i<myArray.size();i++) {
   if (myArray.get(i) == null) {
      List<String> emptyComponent = new ArrayList<String>() {
         { add(""); }
      };
      myArray.set(i,emptyComponent);
   }
}
Walter answered 10/3, 2021 at 23:31 Comment(0)
W
0
    public  void saveUserName(Context con,String username)
    {
        try
        {
            usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
            usernameEditor = usernameSharedPreferences.edit();
            usernameEditor.putInt(PREFS_KEY_SIZE,(USERNAME.size()+1)); 
            int size=USERNAME.size();//USERNAME is arrayList
            usernameEditor.putString(PREFS_KEY_USERNAME+size,username);
            usernameEditor.commit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
    public void loadUserName(Context con)
    {  
        try
        {
            usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
            size=usernameSharedPreferences.getInt(PREFS_KEY_SIZE,size);
            USERNAME.clear();
            for(int i=0;i<size;i++)
            { 
                String username1="";
                username1=usernameSharedPreferences.getString(PREFS_KEY_USERNAME+i,username1);
                USERNAME.add(username1);
            }
            usernameArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, USERNAME);
            username.setAdapter(usernameArrayAdapter);
            username.setThreshold(0);

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
Wilheminawilhide answered 25/3, 2015 at 12:4 Comment(0)
M
0

All of the above answers are correct. :) I myself used one of these for my situation. However when I read the question I found that the OP is actually talking about a different scenario than the title of this post, if I didn't get it wrong.

"I need the array to stick around even if the user leaves the activity and then wants to come back at a later time"

He actually wants the data to be stored till the app is open, irrespective of user changing screens within the application.

"however I don't need the array available after the application has been closed completely"

But once the application is closed data should not be preserved.Hence I feel using SharedPreferences is not the optimal way for this.

What one can do for this requirement is create a class which extends Application class.

public class MyApp extends Application {

    //Pardon me for using global ;)

    private ArrayList<CustomObject> globalArray;

    public void setGlobalArrayOfCustomObjects(ArrayList<CustomObject> newArray){
        globalArray = newArray; 
    }

    public ArrayList<CustomObject> getGlobalArrayOfCustomObjects(){
        return globalArray;
    }

}

Using the setter and getter the ArrayList can be accessed from anywhere withing the Application. And the best part is once the app is closed, we do not have to worry about the data being stored. :)

Magnanimous answered 9/7, 2015 at 9:31 Comment(0)
E
0

It's very simple using getStringSet and putStringSet in SharedPreferences, but in my case, I have to duplicate the Set object before I can add anything to the Set. Or else, the Set will not be saved if my app is force closed. Probably because of the note below in the API below. (It saved though if app is closed by back button).

Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all. http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();

Set<String> outSet = prefs.getStringSet("key", new HashSet<String>());
Set<String> workingSet = new HashSet<String>(outSet);
workingSet.add("Another String");

editor.putStringSet("key", workingSet);
editor.commit();
Electric answered 3/10, 2015 at 4:16 Comment(0)
P
0
Saving and retrieving the ArrayList From SharedPreference
 public static void addToPreference(String id,Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
        ArrayList<String> list = getListFromPreference(context);
        if (!list.contains(id)) {
            list.add(id);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            Set<String> set = new HashSet<>();
            set.addAll(list);
            edit.putStringSet(Constant.LIST, set);
            edit.commit();

        }
    }
    public static ArrayList<String> getListFromPreference(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet(Constant.LIST, null);
        ArrayList<String> list = new ArrayList<>();
        if (set != null) {
            list = new ArrayList<>(set);
        }
        return list;
    }
Prayer answered 22/2, 2018 at 10:17 Comment(2)
Will this preserve order?Lubricity
My understanding is that 'Set' does not preserve order. LinkedHashSet will. And ShardePreferences will not restore a LinkedHashSet nor cast to it. SO I am not sure what will come back.Lubricity
N
0

With Kotlin, for simple arrays and lists, you can do something like:

class MyPrefs(context: Context) {
    val prefs = context.getSharedPreferences("x.y.z.PREFS_FILENAME", 0)
    var listOfFloats: List<Float>
        get() = prefs.getString("listOfFloats", "").split(",").map { it.toFloat() }
        set(value) = prefs.edit().putString("listOfFloats", value.joinToString(",")).apply()
}

and then access the preference easily:

MyPrefs(context).listOfFloats = ....
val list = MyPrefs(context).listOfFloats
Niobous answered 19/4, 2018 at 20:35 Comment(0)
C
0

Please use these two methods for store data in ArrayList in kotlin

fun setDataInArrayList(list: ArrayList<ShopReisterRequest>, key: String, context: Context) {
    val prefs = PreferenceManager.getDefaultSharedPreferences(context)
    val editor = prefs.edit()
    val gson = Gson()
    val json = gson.toJson(list)
    editor.putString(key, json)
    editor.apply()   
}

fun getDataInArrayList(key: String, context: Context): ArrayList<ShopReisterRequest> {
    val prefs = PreferenceManager.getDefaultSharedPreferences(context)
    val gson = Gson()
    val json = prefs.getString(key, null)
    val type = object : TypeToken<ArrayList<ShopReisterRequest>>() {

    }.type
    return gson.fromJson<ArrayList<ShopReisterRequest>>(json, type)
}  
Citreous answered 25/7, 2019 at 18:12 Comment(0)
H
0
public static void WriteSharePrefrence1(Context context, String key, 
ArrayList<HashMap<String, String>> value)
{
    final SharedPreferences preferences = 
    PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(value);
    editor.putString(key, json);
    editor.commit();
}
public static ArrayList<HashMap<String, String>> ReadSharePrefrence1(Context context, 
 String key)
{
    String data;
    Gson gson = new Gson();
    ArrayList<HashMap<String, String>> items = new ArrayList<>();
    final SharedPreferences preferences = 
    PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences.Editor editor = preferences.edit();
    data = preferences.getString(key, "");

    Type type = new TypeToken<ArrayList<HashMap<String, String>>>() {}.getType();
    items = gson.fromJson(data, type);

    return items;
}
Hypoderm answered 26/2, 2020 at 11:22 Comment(0)
J
-1
public class VcareSharedPreference {
  private static VcareSharedPreference sharePref = new VcareSharedPreference(); 
  private static SharedPreferences sharedPreferences; 
  private static SharedPreferences.Editor editor;
  private VcareSharedPreference() {
 } 
public static VcareSharedPreference getInstance(Context context) {
    if (sharedPreferences == null) {
        sharedPreferences = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }
    return sharePref;
 }
public void save(String KEY, String text) {
    editor.putString(KEY, text);
    editor.commit();
}
 public String getValue(String PREFKEY) {
    String text;

    //settings = PreferenceManager.getDefaultSharedPreferences(context);
    text = sharedPreferences.getString(PREFKEY, null);
    return text;
}
public void removeValue(String KEY) {
    editor.remove(KEY);
    editor.commit();
}

public void clearAll() {
    editor.clear();
    editor.commit();
}
public void saveArrayList(String key, ArrayList<ModelWelcome> modelCourses) {
    Gson gson = new Gson();
    String json = gson.toJson(modelCourses);
    editor.putString(key, json);
    editor.apply();
}

public ArrayList<ModelWelcome> getArray(String key) {

    Gson gson = new Gson();
    String json = sharedPreferences.getString(key, null);
    Type type = new TypeToken<ArrayList<ModelWelcome>>() {
    }.getType();
 return gson.fromJson(json, type);}}
Jaquenette answered 26/6, 2019 at 6:32 Comment(1)
this is is the singleton class for sharedpreference for saving any value..ThanksJaquenette

© 2022 - 2024 — McMap. All rights reserved.