I have to save into shared preferences the users alarms which is an object comprising of booleans and ints. There will obviously be multiple alarms saved one after the other. My initial action was to use string builder and save the alarms as one long string seperated by commas and semicolons.
I did that like this:
// Encode the preferences into a single string with "," ready to be unencoded when opening the list again.
StringBuilder alarmString = new StringBuilder();
alarmString.append(alarmHour+","+alarmMinute+","+mondaySelected+","+tuesdaySelected+","+wednesdaySelected+","+
thursdaySelected+","+fridaySelected+","+saturdaySelected+","+sundaySelected);
// Access the shared preferences to see if the user has saved any alarms yet
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("AppData", Context.MODE_PRIVATE);
String alarms = sharedPreferences.getString("AlarmsString", "None");
if (alarms == "None"){
// Save the users alarm preferences to the alarms string encoded string
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("AlarmsString", alarmString.toString());
editor.apply();
Toast.makeText(getActivity(), alarmString, Toast.LENGTH_SHORT).show();
} else {
String alarmStringAppended = alarms + alarmString;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("AlarmsString", alarmStringAppended);
editor.apply();
Toast.makeText(getActivity(), alarmStringAppended, Toast.LENGTH_SHORT).show();
}
I would then break the string back up on the other side.
But then I read it is better to save it as json/gson serialised like this (Incomplete code):
Alarm alarmObject=new Alarm(alarmHour, alarmMinute, mondaySelected, tuesdaySelected,
wednesdaySelected, thursdaySelected, fridaySelected, saturdaySelected, sundaySelected);
SharedPreferences appSharedPrefsave = PreferenceManager
.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor prefsEditor = appSharedPrefsave.edit();
Gson gsonsave = new Gson();
String jsonsave = gsonsave.toJson(alarmObject);
prefsEditor.putString("MyAlarms", jsonsave);
prefsEditor.commit();
SharedPreferences appSharedPrefsRetrieve = PreferenceManager
.getDefaultSharedPreferences(getActivity());
Gson gson = new Gson();
String json = appSharedPrefsRetrieve.getString("MyObject", "");
Alarm mStudentObject = gson.fromJson(json, Alarm.class);
Is there a preferred way and are there any memory issues having to loop through the strings ect or is my original way of doing it just as valid (although long winded).