1 import android.content.Context;
2 import android.content.SharedPreferences;
3
4 import java.util.Set;
5
6 public class Preferences {
7 private static final String PREFERENCES_MAIN = K.app.package_name + ".main";
8 private static Preferences singleton = null;
9
10 private SharedPreferences pref;
11 private SharedPreferences.Editor editor;
12
13 public Preferences (Context context, String prefName) {
14 pref = context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
15 editor = pref.edit();
16 }
17 public Preferences (String prefName) {
18 this(App.getInstance(), prefName);
19 }
20
21 public static Preferences getInstance () {
22 if (singleton == null) {
23 singleton = new Preferences(PREFERENCES_MAIN);
24 }
25 return singleton;
26 }
27
28 public boolean contains (String key) { return pref.contains(key); }
29
30 public boolean get (String key, boolean def) { return pref.getBoolean(key, def); }
31 public int get (String key, int def) { return pref.getInt(key, def); }
32 public long get (String key, long def) { return pref.getLong(key, def); }
33 public float get (String key, float def) { return pref.getFloat(key, def); }
34 public Set<String> get (String key, Set<String> def) { return pref.getStringSet(key, def); }
35 public String get (String key) { return get(key, ""); }
36 public String get (String key, String def) { return pref.getString(key, def == null ? "" : def); }
37
38 public Preferences put (String key, boolean value) { getEditor().putBoolean(key, value); return this; }
39 public Preferences put (String key, int value) { getEditor().putInt(key, value); return this; }
40 public Preferences put (String key, long value) { getEditor().putLong(key, value); return this; }
41 public Preferences put (String key, float value) { getEditor().putFloat(key, value); return this; }
42 public Preferences put (String key, String value) { getEditor().putString(key, value == null ? "" : value); return this; }
43 public Preferences put (String key, Set<String> value) { getEditor().putStringSet(key, value); return this; }
44
45 public Preferences remove (String key) { editor.remove(key); return this; }
46 public Preferences clear () { editor.clear(); return this; }
47
48 public Preferences commit () {
49 // if (editor != null) {
50 // editor.commit();
51 // editor = null;
52 // }
53 editor.commit();
54 return this;
55 }
56
57 private SharedPreferences.Editor getEditor () {
58 if (editor == null) {
59 editor = pref.edit();
60 }
61 return editor;
62 }
63 }