SharedPreferences工具類
import java.util.Map; import java.util.Set;import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor;
/**
- SharedPreferences工具類
@author zouyb / public class SharedPreferencesUtil {
private SharedPreferences sp; private Editor editor; private String name = "mosjoy_chat"; private int mode = Context.MODE_PRIVATE;
public SharedPreferencesUtil(Context context) {
this.sp = context.getSharedPreferences(name, mode); this.editor = sp.edit();
}
/**
- 創建一個工具類,默認打開名字為name的SharedPreferences實例
- @param context
- @param name 唯一標識
@param mode 權限標識 */ public SharedPreferencesUtil(Context context, String name, int mode) { this.sp = context.getSharedPreferences(name, mode); this.editor = sp.edit(); }
/**
- 添加信息到SharedPreferences *
- @param name
- @param map
@throws Exception */ public void add(Map<String, String> map) { Set<String> set = map.keySet(); for (String key : set) {
editor.putString(key, map.get(key));
} editor.commit(); }
/**
- 刪除信息 *
@throws Exception */ public void deleteAll() throws Exception { editor.clear(); editor.commit(); }
/**
刪除一條信息 */ public void delete(String key){ editor.remove(key); editor.commit(); }
/**
- 獲取信息 *
- @param key
- @return
@throws Exception */ public String get(String key){ if (sp != null) {
return sp.getString(key, "");
} return ""; }
/**
- 獲取此SharedPreferences的Editor實例
- @return
*/
public Editor getEditor() {
return editor;
}
}</pre>