package com.camilstaps.common; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.camilstaps.taize.DailyReading; import org.json.JSONException; import java.text.ParseException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Created by camilstaps on 11-4-15. */ public class DatedStringPreferenceSet { public static Set get(Context context, String key, Class type) { Set set = new HashSet<>(); for (String s : PreferenceManager.getDefaultSharedPreferences(context).getStringSet(key, new HashSet())) { try { set.add(type.cast(DatedString.fromString(s, type))); } catch (JSONException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } return set; } public static void put(Context context, String key, Set set) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); Set putSet = new HashSet<>(); for (DatedString item : set) { putSet.add(item.toString()); } editor.putStringSet(key, putSet); editor.apply(); } public static void add(Context context, String key, DatedString object) { Set set = (Set) DatedStringPreferenceSet.get(context, key, DatedString.class); set.add(object); DatedStringPreferenceSet.put(context, key, (Set) set); } public static void update(Context context, String key, DatedString object) { Set set = (Set) get(context, key, object.getClass()); Iterator iterator = set.iterator(); boolean add = false; while (iterator.hasNext()) { DatedString this_object = iterator.next(); if (this_object.getDate().equals(object.getDate())) { iterator.remove(); add = true; } } if (add) { set.add(object); } put(context, key, set); } public static boolean has(Context context, String key, Date date) { Set set = (Set) get(context, key, DatedString.class); for (DatedString item : set) { if (item.getDate().equals(date)) { return true; } } return false; } public static void updateOrAdd(Context context, String key, DatedString object) { if (has(context, key, object.getDate())) { update(context, key, object); } else { add(context, key, object); } } public static void clear(Context context, String key) { put(context, key, new HashSet()); } public static void remove(Context context, String key, Date date) { Set set = (Set) get(context, key, DatedString.class); Iterator iterator = set.iterator(); boolean add = false; while (iterator.hasNext()) { DatedString this_object = iterator.next(); if (this_object.getDate().equals(date)) { iterator.remove(); } } put(context, key, set); } }