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
Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment. getDataDirectory() .
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.
Jetpack DataStore is a new and improved data storage solution aimed at replacing SharedPreferences. Built on Kotlin coroutines and Flow, DataStore provides two different implementations: Data is stored asynchronously, consistently, and transactionally, overcoming most of the drawbacks of SharedPreferences.
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.
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