I have an ArrayList
of objects that have a name and an icon pointer and I want to save it in SharedPreferences
. How can I do?
NOTE: I don't want to use Database
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.
We can store fields of any Object to shared preference by serializing the object to String.
Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage.
Regardless of the API level, Check String arrays and Object arrays in SharedPreferences
SAVE ARRAY
public boolean saveArray(String[] array, String arrayName, Context mContext) { SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0); SharedPreferences.Editor editor = prefs.edit(); editor.putInt(arrayName +"_size", array.length); for(int i=0;i<array.length;i++) editor.putString(arrayName + "_" + i, array[i]); return editor.commit(); }
LOAD ARRAY
public String[] loadArray(String arrayName, Context mContext) { SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0); int size = prefs.getInt(arrayName + "_size", 0); String array[] = new String[size]; for(int i=0;i<size;i++) array[i] = prefs.getString(arrayName + "_" + i, null); return array; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With