-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSPUtils.java
More file actions
102 lines (90 loc) · 3.09 KB
/
SPUtils.java
File metadata and controls
102 lines (90 loc) · 3.09 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.hht.baselib;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Map;
/**
* Created by RealMo on 2019/6/25
*/
public class SPUtils {
/**
* 保存数据
*/
public static void put(Context context, String fileName,String key, Object obj,boolean async) {
SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (obj instanceof Boolean) {
editor.putBoolean(key, (Boolean) obj);
} else if (obj instanceof Float) {
editor.putFloat(key, (Float) obj);
} else if (obj instanceof Integer) {
editor.putInt(key, (Integer) obj);
} else if (obj instanceof Long) {
editor.putLong(key, (Long) obj);
} else {
editor.putString(key, (String) obj);
}
if(async){
editor.apply();
}else{
editor.commit();
}
}
/**
* 获取指定数据
*/
public static Object get(Context context, String fileName,String key, Object defaultObj) {
SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
if (defaultObj instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultObj);
} else if (defaultObj instanceof Float) {
return sp.getFloat(key, (Float) defaultObj);
} else if (defaultObj instanceof Integer) {
return sp.getInt(key, (Integer) defaultObj);
} else if (defaultObj instanceof Long) {
return sp.getLong(key, (Long) defaultObj);
} else if (defaultObj instanceof String) {
return sp.getString(key, (String) defaultObj);
}
return null;
}
/**
* 删除指定数据
*/
public static void remove(Context context, String fileName,String key,boolean async) {
SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
if(async){
editor.apply();
}else{
editor.commit();
}
}
/**
* 返回所有键值对
*/
public static Map<String, ?> getAll(Context context,String fileName) {
SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
return sp.getAll();
}
/**
* 删除所有数据
*/
public static void clear(Context context,String fileName,boolean async) {
SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
if(async){
editor.apply();
}else{
editor.commit();
}
}
/**
* 检查key对应的数据是否存在
*/
public static boolean contains(Context context,String fileName, String key) {
SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
return sp.contains(key);
}
}