How to save Calendar data in shared preferences : Android

android, arraylist, sharedpreferences

Solution

You will have to convert each of your calendar to long using method Calendar.getTimeInMillis() and then save it in your preference using method putLong(key, long). You will have to change the key for each entry. Here is an example:

    SharedPreferences shrdPref = getSharedPreferences("sharePref",MODE_PRIVATE);
    SharedPreferences.Editor prefEditor = shardPref.edit();
       for(int i = 0; i<list.size();i++){
          long millis = list.get(i).getTimeInMillis();
          prefEditor.putLong("calendar"+i,millis);
          prefEditor.commit();
       }

You would then retrieve them with:

int i =0;
while(shrdPref.getLong("calendar"+i,0)!=0){
   Calendar cal = new GregorianCalendar();
   cal.setTimeInMillis(shrdPref.getLong("calendar"+i,0));
   list.add(cal);
   i++;
}

Bit of a hack, not sure if it works, try it and let me know.

Problem

I have a `ArrayList` of `Calendar` type, And I need to save its data into `SharedPreferences`. I can save `String` `ArrayList` data by using this code: ``` Set<String> setName = new HashSet<String>(); setName.addAll(ignoredProcesses); SharedPreferences shrdPref = getSharedPreferences("sharePref", MODE_PRIVATE); SharedPreferences.Editor prefEditor = shardPref.edit(); prefEditor.putStringSet("keyValue", setName); prefEditor.commit(); ``` But if I'm following the same approach to save `Calendar` data, I'm getting error to change `Set` type to `String`. How can I save `ArrayList <Calendar> list = new ArrayList<Calendar>();` into `SharedPreferences` and how I to get it back from `SharedPrefernces`. Your help will be very appreciated. Thank you

Original source