SharedPreferences工具類

fpy7 9年前發布 | 2K 次閱讀 Java Android

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>
 本文由用戶 fpy7 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!