android本地存储工具类封装

package com.coral3.common_module.utils;

import android.app.Application;
import android.content.SharedPreferences;

/**
 * @author 蓝之静云
 * @description 本地存储工具类
 * @date 2021-12-*
 */
public class SharedPrefUtils {

    private static SharedPrefUtils instance;
    private SharedPreferences sp;

    private SharedPrefUtils(Application application) {
        sp = application.getSharedPreferences(
                application.getPackageName(), 0);
    }

    public static SharedPrefUtils getInstance() {
        if (instance == null) {
            synchronized (SharedPrefUtils.class) {
                if (instance == null) {
                    instance = new SharedPrefUtils((Application) InitUtil.getContext().getApplicationContext());
                }
            }
        }
        return instance;
    }

    public void put(String key, String value) {
        sp.edit().putString(key, value).commit();
    }

    public String get(String key, String defValue) {
        return sp.getString(key, defValue);
    }

    public void put(String key, Integer value) {
        sp.edit().putInt(key, value).commit();
    }

    public Integer get(String key, Integer defValue) {
        return sp.getInt(key, defValue);
    }

    public void put(String key, Float value) {
        sp.edit().putFloat(key, value).commit();
    }

    public Float get(String key, Float defValue) {
        return sp.getFloat(key, defValue);
    }

    public void put(String key, Long value) {
        sp.edit().putLong(key, value).commit();
    }

    public Long get(String key, Long defValue) {
        return sp.getLong(key, defValue);
    }

    public void put(String key, boolean value) {
        sp.edit().putBoolean(key, value).commit();
    }

    public Boolean get(String key, boolean defValue) {
        return sp.getBoolean(key, defValue);
    }

    public void remove(String key) {
        try {
            sp.edit().remove(key).commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值