完美的sharedPreference工具类

github上大神们开源的各种Android工具类https://github.com/android-quick-dev/NonViewUtils

这篇记录下SPUtil工具类。

首先构建一个内部类,该类的作用是优先使用SharedPreferences的apply方法,如果找不到则使用commit方法。这两个方法的区别在于:

  1. apply没有返回值而commit返回boolean表明修改是否提交成功

  2. apply是将修改数据原子提交到内存, 而后异步真正提交到硬件磁盘, 而commit是同步的提交到硬件磁盘,因此,在多个并发的提交commit的时候,他们会等待正在处理的commit保存到磁盘后在操作,从而降低了效率。而apply只是原子的提交到内容,后面有调用apply的函数的将会直接覆盖前面的内存数据,这样从一定程度上提高了很多效率。

  3. apply方法不会提示任何失败的提示。

由于在一个进程中,sharedPreference是单实例,一般不会出现并发冲突,如果对提交的结果不关心的话,建议使用apply,当然需要确保提交成功且有后续操作的话,还是需要用commit的。

内部类:

private static classSharedPreferencesCompat{

//查看SharedPreferences是否有apply方法

private static finalMethodsApplyMethod=findApply();

private staticMethodfindApply(){

try{

Class cls=SharedPreferences.class;

returncls.getMethod("apply");

}catch(NoSuchMethodException e) {

e.printStackTrace();

}

return null;

}

/**

* 如果找到则使用apply执行,否则使用commit

*/

public static voidapply(SharedPreferences.Editor editor){

try{

if(sApplyMethod!=null) {

sApplyMethod.invoke(editor);

return;

}

}catch(IllegalAccessException e) {

e.printStackTrace();

}catch(InvocationTargetException e) {

e.printStackTrace();

}

editor.commit();

}

}

保存的文件名是通过包名+_preferences

/** * SharedPreferences存储在sd卡中的文件名字 
*/private static String getSpName(Context context) {    
return context.getPackageName() + "_preferences";
}

然后保存和获取数据格式通过Object来实现:

/** * /**
     * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
     */
    public static void putAndApply(Context context ,String key ,Object o){

        SharedPreferences sp=context.getSharedPreferences(getSpName(context),Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();

        if(o instanceof String){
            editor.putString(key,(String)o);
        }else if(o instanceof Integer){
            editor.putInt(key, (Integer) o);
        }else if(o instanceof Float){
            editor.putFloat(key,(Float)o);
        }else if(o instanceof Long){
            editor.putLong(key, (Long) o);
        }else if (o instanceof Boolean){
            editor.putBoolean(key, (Boolean) o);
        }else {
            editor.putString(key, o.toString());
        }
        //提交
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
     */
    public static Object get(Context context, String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);

        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        } else {
            return null;
        }
    }

还有几个删除、清空、判断某个key以及获取所有数据的方法:

 /**
     * 移除某个key值已经对应的值
     */
    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除所有数据
     */
    public static void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查询某个key是否已经存在
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    /**
     * 返回所有的键值对
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);
        return sp.getAll();
    }

最后我将所有代码贴出来,以上所有方法都在一个方法类里面:

package com.utils.utils;

import android.content.Context;
import android.content.SharedPreferences;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by IT_mo on 2016/5/12.
 * QQ:420733721
 */
public class SPUtil {

    /**
     * SharedPreferences存储在sd卡中的文件名字
     */
    private static String getSpName(Context context) {
        return context.getPackageName() + "_preferences";
    }

    /**
     * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
     */
    public static void putAndApply(Context context ,String key ,Object o){

        SharedPreferences sp=context.getSharedPreferences(getSpName(context),Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();

        if(o instanceof String){
            editor.putString(key,(String)o);
        }else if(o instanceof Integer){
            editor.putInt(key, (Integer) o);
        }else if(o instanceof Float){
            editor.putFloat(key,(Float)o);
        }else if(o instanceof Long){
            editor.putLong(key, (Long) o);
        }else if (o instanceof Boolean){
            editor.putBoolean(key, (Boolean) o);
        }else {
            editor.putString(key, o.toString());
        }
        //提交
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
     */
    public static Object get(Context context, String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);

        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        } else {
            return null;
        }
    }

    /**
     * 移除某个key值已经对应的值
     */
    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除所有数据
     */
    public static void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查询某个key是否已经存在
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    /**
     * 返回所有的键值对
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);
        return sp.getAll();
    }

    //*************************************内部类*******************************************//

    /**
     *优先使用SharedPreferences的apply方法,如果找不到则使用commit方法
     */
    private static class SharedPreferencesCompat{

        //查看SharedPreferences是否有apply方法
        private static final Method sApplyMethod=findApply();

        private static Method findApply(){

            try {
                Class cls=SharedPreferences.class;
                return cls.getMethod("apply");
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            return null;
        }
        /**
         * 如果找到则使用apply执行,否则使用commit
         */
        public static void apply(SharedPreferences.Editor editor){

                try {
                    if(sApplyMethod!=null) {
                        sApplyMethod.invoke(editor);
                        return;
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }

            editor.commit();
            }

    }

}


作者:Mr_默
链接:http://www.jianshu.com/p/a818379ded3d
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值