sharepreference管理工具类

自动分析类型,保存数据

/**
 * 缓存管理器
 */

public class CacheManager {
    private static SharedPreferences sp = null;
    private static Context context;

    /**
     * 读取缓存的信息
     */
    public static void initCache(Context context) {
        CacheManager.context = context;
        sp = context.getSharedPreferences(Constant.SETTINGS_KEY, Context.MODE_PRIVATE);
    }

    /**
     * 向sharepreferences存入键值对
     */
    public static boolean addCache(String[] keys, Object[] values) {
        if (keys.length != values.length) {
            return false;
        }
        SharedPreferences sp = context.getSharedPreferences(Constant.SETTINGS_KEY, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        for (int i = 0; i < keys.length; i++) {
            if (values[i] instanceof String) {
                editor.putString(keys[i], (String) values[i]);
            } else if (values[i] instanceof Boolean) {
                editor.putBoolean(keys[i], (Boolean) values[i]);
            } else if (values[i] instanceof Integer) {
                editor.putInt(keys[i], (Integer) values[i]);
            } else if (values[i] instanceof Long) {
                editor.putLong(keys[i], (Long) values[i]);
            } else if (values[i] instanceof Float) {
                editor.putFloat(keys[i], (Float) values[i]);
            }
        }
        editor.commit();
        return true;
    }

    public static String getString(String key, String defaultValue) {
        if (sp == null) {
            return defaultValue;
        }
        return sp.getString(key, defaultValue);
    }

    public static boolean getBoolean(String key, boolean defaultValue) {
        if (sp == null) {
            return defaultValue;
        }
        return sp.getBoolean(key, defaultValue);
    }

    public static int getInt(String key, int defaultValue) {
        if (sp == null) {
            return defaultValue;
        }
        return sp.getInt(key, defaultValue);
    }

    public static long getLong(String key) {
        if (sp == null) {
            return 0;
        }
        return sp.getLong(key, 0L);
    }

    public static boolean remove(String key) {
        if (sp == null) {
            return false;
        }
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        editor.commit();
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值