How to save calendar data in general preferences: Android

I have an ArrayList type Calendar , and I need to save its data in SharedPreferences . I can save String ArrayList data 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 follow the same approach for saving Calendar data, I get an error to change the Set type to String .

How can I save ArrayList <Calendar> list = new ArrayList<Calendar>(); in SharedPreferences and how do I get it back from SharedPrefernces . Your help will be greatly appreciated. thank you

+4
source share
1 answer

You will need to convert each your calendar to a long one using the Calendar.getTimeInMillis () method, and then save it in your preferences using the putLong (key, long) method. You will need 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(); } 

Then you will get 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++; } 

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

+5
source

Source: https://habr.com/ru/post/1494971/


All Articles