Android SharedPreferences存储基本用法

这里面有基本数据类型、List集合、Map集合、对象都在这了 工具类里面 可以直接拿来用

简书图片
    public class SpUtil {  
      
        private static SharedPreferences sp;  
      
        private static SharedPreferences getSp(Context context) {  
            if (sp == null) {  
                sp = context.getSharedPreferences("SpUtil", Context.MODE_PRIVATE);  
            }  
            return sp;  
        }  
      
      
        /** 
         * 存入字符串 
         * 
         * @param context 上下文 
         * @param key     字符串的键 
         * @param value   字符串的值 
         */  
        public static void putString(Context context, String key, String value) {  
            SharedPreferences preferences = getSp(context);  
            //存入数据  
            Editor editor = preferences.edit();  
            editor.putString(key, value);  
            editor.commit();  
        }  
      
        /** 
         * 获取字符串 
         * 
         * @param context 上下文 
         * @param key     字符串的键 
         * @return 得到的字符串 
         */  
        public static String getString(Context context, String key) {  
            SharedPreferences preferences = getSp(context);  
            return preferences.getString(key, "");  
        }  
      
        /** 
         * 获取字符串 
         * 
         * @param context 上下文 
         * @param key     字符串的键 
         * @param value   字符串的默认值 
         * @return 得到的字符串 
         */  
        public static String getString(Context context, String key, String value) {  
            SharedPreferences preferences = getSp(context);  
            return preferences.getString(key, value);  
        }  
      
        /** 
         * 保存布尔值 
         * 
         * @param context 上下文 
         * @param key     键 
         * @param value   值 
         */  
        public static void putBoolean(Context context, String key, boolean value) {  
            SharedPreferences sp     = getSp(context);  
            Editor            editor = sp.edit();  
            editor.putBoolean(key, value);  
            editor.commit();  
        }  
      
        /** 
         * 获取布尔值 
         * 
         * @param context  上下文 
         * @param key      键 
         * @param defValue 默认值 
         * @return 返回保存的值 
         */  
        public static boolean getBoolean(Context context, String key, boolean defValue) {  
            SharedPreferences sp = getSp(context);  
            return sp.getBoolean(key, defValue);  
        }  
      
        /** 
         * 保存long值 
         * 
         * @param context 上下文 
         * @param key     键 
         * @param value   值 
         */  
        public static void putLong(Context context, String key, long value) {  
            SharedPreferences sp     = getSp(context);  
            Editor            editor = sp.edit();  
            editor.putLong(key, value);  
            editor.commit();  
        }  
      
        /** 
         * 获取long值 
         * 
         * @param context  上下文 
         * @param key      键 
         * @param defValue 默认值 
         * @return 保存的值 
         */  
        public static long getLong(Context context, String key, long defValue) {  
            SharedPreferences sp = getSp(context);  
            return sp.getLong(key, defValue);  
        }  
      
        /** 
         * 保存int值 
         * 
         * @param context 上下文 
         * @param key     键 
         * @param value   值 
         */  
        public static void putInt(Context context, String key, int value) {  
            SharedPreferences sp     = getSp(context);  
            Editor            editor = sp.edit();  
            editor.putInt(key, value);  
            editor.commit();  
        }  
      
        /** 
         * 获取long值 
         * 
         * @param context  上下文 
         * @param key      键 
         * @param defValue 默认值 
         * @return 保存的值 
         */  
        public static int getInt(Context context, String key, int defValue) {  
            SharedPreferences sp = getSp(context);  
            return sp.getInt(key, defValue);  
        }  
      
        /** 
         * 保存对象 
         * 
         * @param context 上下文 
         * @param key     键 
         * @param obj     要保存的对象(Serializable的子类) 
         * @param <T>     泛型定义 
         */  
        public static <T extends Serializable> void putObject(Context context, String key, T obj) {  
            try {  
                put(context, key, obj);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
      
        /** 
         * 获取对象 
         * 
         * @param context 上下文 
         * @param key     键 
         * @param <T>     指定泛型 
         * @return 泛型对象 
         */  
        public static <T extends Serializable> T getObject(Context context, String key) {  
            try {  
                return (T) get(context, key);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            return null;  
        }  
      
        /** 
         * 存储List集合 
         * @param context 上下文 
         * @param key 存储的键 
         * @param list 存储的集合 
         */  
        public static void putList(Context context, String key, List<? extends Serializable> list) {  
            try {  
                put(context, key, list);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
      
        /** 
         * 获取List集合 
         * @param context 上下文 
         * @param key 键 
         * @param <E> 指定泛型 
         * @return List集合 
         */  
        public static <E extends Serializable> List<E> getList(Context context, String key) {  
            try {  
                return (List<E>) get(context, key);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            return null;  
        }  
      
        /** 
         * 存储Map集合 
         * @param context 上下文 
         * @param key 键 
         * @param map 存储的集合 
         * @param <K> 指定Map的键 
         * @param <V> 指定Map的值 
         */  
        public static <K extends Serializable, V extends Serializable> void putMap(Context context,  
                String key, Map<K, V> map)  
        {  
            try {  
                put(context, key, map);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
      
        public static <K extends Serializable, V extends Serializable> Map<K, V> getMap(Context context,  
                String key)  
        {  
            try {  
                return (Map<K, V>) get(context, key);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            return null;  
        }  
      
        /**存储对象*/  
        private static void put(Context context, String key, Object obj)  
                throws IOException  
        {  
            if (obj == null) {//判断对象是否为空  
                return;  
            }  
            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
            ObjectOutputStream    oos  = null;  
            oos = new ObjectOutputStream(baos);  
            oos.writeObject(obj);  
            // 将对象放到OutputStream中  
            // 将对象转换成byte数组,并将其进行base64编码  
            String objectStr = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));  
            baos.close();  
            oos.close();  
      
            putString(context, key, objectStr);  
        }  
      
        /**获取对象*/  
        private static Object get(Context context, String key)  
                throws IOException, ClassNotFoundException  
        {  
            String wordBase64 = getString(context, key);  
            // 将base64格式字符串还原成byte数组  
            if (TextUtils.isEmpty(wordBase64)) { //不可少,否则在下面会报java.io.StreamCorruptedException  
                return null;  
            }  
            byte[]               objBytes = Base64.decode(wordBase64.getBytes(), Base64.DEFAULT);  
            ByteArrayInputStream bais     = new ByteArrayInputStream(objBytes);  
            ObjectInputStream    ois      = new ObjectInputStream(bais);  
            // 将byte数组转换成product对象  
            Object obj = ois.readObject();  
            bais.close();  
            ois.close();  
            return obj;  
        }  
    }  



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容