What is the best way to save an ArrayList
of strings to SharedPreferences
in API level 8? The only way i can think of now is to save all of the str
If you are using an api (like level 8) where you cant use put/getStringSet(), then this is a possible solution, but this is very expensive and not flexible if you want to store bigger lists. I mean creating a map like datastructure for a simple array-like structure creates a huge overhead, if preformance is important.
To save it:
public static void writeList(Context context, List list, String prefix)
{
SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
int size = prefs.getInt(prefix+"_size", 0);
// clear the previous data if exists
for(int i=0; i
To retrieve it:
public static List readList (Context context, String prefix)
{
SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
int size = prefs.getInt(prefix+"_size", 0);
List data = new ArrayList(size);
for(int i=0; i
And to actually use it:
List animals = new ArrayList();
animals.add("cat");
animals.add("bear");
animals.add("dog");
writeList(someContext, animals, "animal");
And to retrieve it:
List animals = readList (someContext, "animal");
If you are not limited to use SharedPreferences, consider using SQLiteDatabase!