共享一个SharedPreferences存储工具类


package ***.utils;

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

/**
 * date : 2017/8/7
 * author : bianyaoyao
 * Description :SharedPreferences存储工具类
 */

public class PrefUtils {
    private  static  String name = "Config";
    public static void putBoolean(Context ctx, String key, boolean value) {
        SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
        sp.edit().putBoolean(key, value).commit();
    }

    public static boolean getBoolean(Context ctx, String key, boolean defValue) {
        SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
        return sp.getBoolean(key, defValue);
    }

    public static void putString(Context ctx, String key, String value) {
        SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
        sp.edit().putString(key, value).commit();
    }

    public static String getString(Context ctx, String key, String defValue) {
        SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
        return sp.getString(key, defValue);
    }

    public static void putInt(Context ctx, String key, int value) {
        SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
        sp.edit().putInt(key, value).commit();
    }

    public static int getInt(Context ctx, String key, int defValue) {
        SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
        return sp.getInt(key, defValue);
    }

    //删除某个键值对
    public static void remove(Context ctx, String key) {
        SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
        sp.edit().remove(key).commit();
    }
}

关于mode参数   一般都取MODE_PRIVATE,这里的MODE_PRIVATE 和openFileOutput方法里的MODE_PRIVATE 是一个意思。官方已经废除了MODE_WORLD_READABLE 和 MODE_WORLD_WRITEABLE  这两个参数意思分别是允许其他应用读取和写入我们的sharedPreferences,官方也是为用户的安全着想


使用:

PrefUtils.putString(LoginActivity.this, "id", "21u34445555"); 
PrefUtils.getString(LoginActivity.this, "id", "");

当然,上面的String 类型的id 字段可以新建一个文件 ,避免字符串过长拼写错误引起的尴尬问题

public interface GlobalConstants {
    String PREF_ID                    = "id";
}
PrefUtils.getString(LoginActivity.this, GlobalConstants.PREF_ID, "");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值