Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add an array or object to SharedPreferences on Android

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

like image 368
zsniperx Avatar asked Oct 06 '10 20:10

zsniperx


People also ask

Can we store array in SharedPreferences?

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.

Can we store object in SharedPreferences Android?

We can store fields of any Object to shared preference by serializing the object to String.

Which type of data you can store in SharedPreferences in Android?

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.


1 Answers

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;   }   
like image 110
Sherif elKhatib Avatar answered Sep 18 '22 19:09

Sherif elKhatib