记一个比较全面的sp(SharedPreferencesUtils)工具类

public class SharedPreferencesUtils {

    private static volatile SharedPreferencesUtils sSharedPreferencesUtils;

    private Map<String, SharedPreferences> mSharedPreferenceMap;

    /**
     * 不能直接获得实例化对象
     */
    private SharedPreferencesUtils() {
        mSharedPreferenceMap = new HashMap<>();
    }

    /**
     * 单例设计模式
     */
    public static SharedPreferencesUtils getInstance() {
        if (sSharedPreferencesUtils == null) {
            synchronized (SharedPreferencesUtils.class) {
                if (sSharedPreferencesUtils == null) {
                    sSharedPreferencesUtils = new SharedPreferencesUtils();
                }
            }
        }

        return sSharedPreferencesUtils;
    }

    /**
     * 在Application中进行初始化一个SharedPreferences
     *
     * @param context 不能为空,否则抛出NullPointerException异常
     * @param sharedPreferencesName SharedPreferences的名字,不能为空,
     *         否则抛出NullPointerException异常
     */
    public void init(Context context, String sharedPreferencesName) {
        List<String> sharedPreferencesNames = new ArrayList<>();
        sharedPreferencesNames.add(sharedPreferencesName);

        init(context, sharedPreferencesNames);
    }

    /**
     * 在Application中进行初始化多个SharedPreferences
     *
     * @param context 不能为空,否则抛出NullPointerException异常
     * @param sharedPreferencesNames 存放SharedPreferences名字的集合,集合不能为空,并且集合中的数据也不能为空
     *         否则抛出NullPointerException异常
     */
    public void init(Context context, List<String> sharedPreferencesNames) {
        if (context == null) {
            throw new NullPointerException("初始化的Context不能为null");
        }

        if (sharedPreferencesNames == null || sharedPreferencesNames.isEmpty()) {
            throw new NullPointerException("SharedPreferences的集合不能为空");
        }

        for (String sharedPreferencesName : sharedPreferencesNames) {
            checkNonemptyName(sharedPreferencesName);

            mSharedPreferenceMap.put(sharedPreferencesName,
                    context.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE));
        }
    }

    /**
     * 指定SharedPreferences中根据key值添加或更新一条数据
     *
     * @param sharedPreferencesName 指定的SharedPreferences的名字,不能为空,否则抛出NullPointerException
     * @param key key值不存在添加数据,key值存在更新数据,不能为空,否则抛出NullPointerException
     * @param value 要添加或更新的一条数据,不能为空,否则抛出NullPointerException
     *         类型只能为八大基本数据类型、String、Set,否则抛出IllegalArgumentException
     */
    public void putData(String sharedPreferencesName, String key, Object value) {
        checkNonemptyName(sharedPreferencesName);

        SharedPreferences sharedPreferences = mSharedPreferenceMap.get(sharedPreferencesName);
        if (sharedPreferences == null) {
            return;
        }
        SharedPreferences.Editor editor = sharedPreferences.edit();

        putData(editor, key, value);

        editor.apply();
    }

    /**
     * 指定SharedPreferences中根据key值批量添加或更新数据
     *
     * @param sharedPreferencesName 指定的SharedPreferences的名字,不能为空,否则抛出NullPointerException
     * @param dataMap 存放数据的Map集合,不能为空,并且集合中的数据不能为空,否则抛出NullPointerException
     *         类型只能为八大基本数据类型、String、Set,否则抛出IllegalArgumentException
     */
    public void putDataMap(String sharedPreferencesName, Map<String, Object> dataMap) {
        checkNonemptyName(sharedPreferencesName);

        if (dataMap == null || dataMap.isEmpty()) {
            return;
        }

        SharedPreferences sharedPreferences = mSharedPreferenceMap.get(sharedPreferencesName);
        if (sharedPreferences == null) {
            return;
        }
        SharedPreferences.Editor editor = sharedPreferences.edit();

        //遍历Map集合批量添加数据
        for (Map.Entry<String, Object> entity : dataMap.entrySet()) {
            putData(editor, entity.getKey(), entity.getValue());
        }

        editor.apply();
    }

    /**
     * 指定SharedPreferences中根据key值删除一条数据
     *
     * @param sharedPreferencesName 指定的SharedPreferences的名字,不能为空,否则抛出NullPointerException
     * @param key 要删除的key值和与其对应的数据,不能为空,否则抛出NullPointerException
     */
    public void removeValueByKey(String sharedPreferencesName, String key) {
        checkNonemptyName(sharedPreferencesName);

        checkNonemptyName(key);

        SharedPreferences sharedPreferences = mSharedPreferenceMap.get(sharedPreferencesName);
        if (sharedPreferences == null) {
            return;
        }

        sharedPreferences.edit()
                .remove(key)
                .apply();
    }

    /**
     * 清除指定SharedPreferences中的所有数据(慎用)
     *
     * @param sharedPreferencesName 指定的SharedPreferences的名字,不能为空,否则抛出NullPointerException
     */
    public void clearAllData(String sharedPreferencesName) {
        checkNonemptyName(sharedPreferencesName);

        SharedPreferences sharedPreferences = mSharedPreferenceMap.get(sharedPreferencesName);
        if (sharedPreferences == null) {
            return;
        }

        sharedPreferences.edit()
                .clear()
                .apply();
    }

    /**
     * 指定SharedPreferences中根据key值获得与其对应的值
     *
     * @param sharedPreferencesName 指定的SharedPreferences的名字,不能为空,否则抛出NullPointerException
     * @param key key值,不能为空,否则抛出NullPointerException
     * @param defaultValue 默认值,不能为空,否则抛出NullPointerException
     *         类型只能为八大基本数据类型、String、Set,否则抛出IllegalArgumentException
     *
     * @return 返回值的类型与defaultValue类型相同,key值存在返回对应的值,不存在返回默认值
     */
    @SuppressWarnings("unchecked")
    public <T> T getValueByKey(String sharedPreferencesName, String key, T defaultValue) {
        SharedPreferences sharedPreferences = mSharedPreferenceMap.get(sharedPreferencesName);
        if (sharedPreferences == null) {
            throw new NullPointerException("SharedPreferences为空");
        }

        if (defaultValue instanceof Byte) {
            return (T)Byte.valueOf((byte)sharedPreferences.getInt(key, (Byte)defaultValue));
        } else if (defaultValue instanceof Short) {
            return (T)Short.valueOf((byte)sharedPreferences.getInt(key, (Short)defaultValue));
        } else if (defaultValue instanceof Integer) {
            return (T)(Integer)sharedPreferences.getInt(key, (Integer)defaultValue);
        } else if (defaultValue instanceof Long) {
            return (T)(Long)sharedPreferences.getLong(key, (Long)defaultValue);
        } else if (defaultValue instanceof Float) {
            return (T)(Float)sharedPreferences.getFloat(key, (Float)defaultValue);
        } else if (defaultValue instanceof Double) {
            return (T)Double.valueOf(String.valueOf(
                    sharedPreferences.getFloat(key, ((Double)defaultValue).floatValue())));
        } else if (defaultValue instanceof Boolean) {
            return (T)(Boolean)sharedPreferences.getBoolean(key, (Boolean)defaultValue);
        } else if (defaultValue instanceof Character) {
            String stringValue = sharedPreferences.getString(key, String.valueOf(defaultValue));
            return (T)(Character)(stringValue == null ? ' ' : stringValue.charAt(0));
        } else if (defaultValue instanceof String) {
            return (T)sharedPreferences.getString(key, (String)defaultValue);
        } else if (defaultValue instanceof Set<?>) {
            return (T)sharedPreferences.getStringSet(key, (Set<String>)defaultValue);
        } else {
            throw new IllegalArgumentException("defaultValue的参数类型有误");
        }
    }

    /**
     * 检查SharedPreferences是否为空,为空直接抛出NullPointerException
     */
    private void checkNonemptyName(String sharedPreferencesName) {
        if (TextUtils.isEmpty(sharedPreferencesName)) {
            throw new NullPointerException("SharedPreferences的名字不能为空");
        }
    }

    /**
     * 通过Editor向SharedPreferences中添加或更新一条数据,未提交
     */
    @SuppressWarnings("unchecked")
    private void putData(SharedPreferences.Editor editor, String key, Object value) {
        checkNonemptyName(key);

        if (value == null) {
            throw new NullPointerException("数据不能为空");
        }

        if (value instanceof Byte) {
            editor.putInt(key, (byte)value);
        } else if (value instanceof Short) {
            editor.putInt(key, (short)value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (int)value);
        } else if (value instanceof Long) {
            editor.putLong(key, (long)value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (float)value);
        } else if (value instanceof Double) {
            editor.putFloat(key, ((Double)value).floatValue());
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (boolean)value);
        } else if (value instanceof Character) {
            editor.putString(key, String.valueOf(value));
        } else if (value instanceof String) {
            editor.putString(key, (String)value);
        } else if (value instanceof Set<?>) {
            editor.putStringSet(key, (Set<String>)value);
        } else {
            throw new IllegalArgumentException("defaultValue的参数类型有误");
        }
    }

}

你可能感兴趣的:(笔记)