SharedPreferencesUtil

封装了SharedPreferences ,方便调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
public class SharedPreferencesUtil {
public static String getString(Context context, String key,
final String defaultValue) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
return settings.getString(key, defaultValue);
}
public static void setString(Context context, final String key,
final String value) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
settings.edit().putString(key, value).apply();
}
public static boolean getBoolean(Context context, final String key,
final boolean defaultValue) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
return settings.getBoolean(key, defaultValue);
}
public static boolean hasKey(Context context, final String key) {
return PreferenceManager.getDefaultSharedPreferences(context).contains(
key);
}
public static void setBoolean(Context context, final String key,
final boolean value) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
settings.edit().putBoolean(key, value).apply();
}
public static void setInt(Context context, final String key,
final int value) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
settings.edit().putInt(key, value).apply();
}
public static int getInt(Context context, final String key,
final int defaultValue) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
return settings.getInt(key, defaultValue);
}
public static void setFloat(Context context, final String key,
final float value) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
settings.edit().putFloat(key, value).apply();
}
public static float getFloat(Context context, final String key,
final float defaultValue) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
return settings.getFloat(key, defaultValue);
}
public static void setLong(Context context, final String key,
final long value) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
settings.edit().putLong(key, value).apply();
}
public static long getLong(Context context, final String key,
final long defaultValue) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
return settings.getLong(key, defaultValue);
}
public static void clear(Context context,
final SharedPreferences p) {
final SharedPreferences.Editor editor = p.edit();
editor.clear();
editor.apply();
}
}


联系作者

我的微信公众号:吴小龙同学,欢迎关注交流,公号回复关键字「1024」有惊喜哦。