android中数据储存的方式一般有5种,
1.保存在data/data/包名下
2.保存在sd卡中
3.保存在中
4.保存在SharedPreferences数据库中
5.保存在contentprovider中
今天来着重介绍一下关于sp的使用问题:
1.获取SharedPreferences对象
sp = getSharedPreferences("config", MODE_PRIVATE);
目录:/data/data/包名/shared_prefs/config.xml
2.保存数据
sp.edit().putString("username","晋锐").putInt("age",23).commit();
3.删除数据
删除一个
sp.edit().remove("age").commit();
删除全部
sp.edit().clear().commit();
4. 获取数据
String username = sp.getString("username",defValue);
附赠常用的 SpUtil工具类 :
public enum SharedPreferenceUtil {
INSTANCE;
private final String PREF_NAME = "CommonSharedPreference";
protected SharedPreferences mSettings;
protected SharedPreferences.Editor mEditor;
private Context mContext;
// 初始化构造
SharedPreferenceUtil() {
mContext = HomeApplication.getInstance().getApplicationContext();
if (mContext == null) {
return;
}
mSettings = mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
mEditor = mSettings.edit();
}
public boolean commit() {
return mEditor.commit();
}
public String getString(String key) {
return mSettings.getString(key, "");
}
public String getString(String key, String defaultValue) {
return mSettings.getString(key, defaultValue);
}
public void saveString(String key, String value) {
mEditor.putString(key, value);
mEditor.commit();
}
public boolean getBoolean(String key, boolean defValue) {
return mSettings.getBoolean(key, defValue);
}
public void saveBoolean(String key, boolean value) {
mEditor.putBoolean(key, value);
mEditor.commit();
}
public int getInt(String key, int defValue) {
return mSettings.getInt(AccountAgent.getUserName() + key, defValue);
}
public void saveInt(String key, int value) {
mEditor.putInt(AccountAgent.getUserName() + key, value);
mEditor.commit();
}
public long getLong(String key, long defValue) {
return mSettings.getLong(AccountAgent.getUserName() + key, defValue);
}
public void saveLong(String key, long value) {
mEditor.putLong(AccountAgent.getUserName() + key, value);
mEditor.commit();
}
public Object getObject(String key, Type type) {
String json = getString(key);
if (!TextUtils.isEmpty(json)) {
try {
Gson gson = new Gson();
return gson.fromJson(json, type);
} catch (JsonParseException e) {
e.printStackTrace();
}
}
return null;
}
public void saveObject(String key, Object obj) {
Gson gson = new Gson();
String objStr = gson.toJson(obj);
saveString(key, objStr);
}
public void removeKey(String key) {
mEditor.remove(key);
mEditor.commit();
}
public void clearKeys() {
mEditor.clear();
mEditor.commit();
}
public boolean isContains(String key) {
return mSettings.contains(key);
}
}