sharedPrefrence保存读取对象

本文介绍了如何使用SharedPreference在Android中保存和读取自定义对象。通过将对象序列化为Base64字符串进行存储,然后反序列化回原始对象。
摘要由CSDN通过智能技术生成
在SharedPrefrence中保存读取对象

private static SharedPreferences mSharedPreferences;

/**
 * 将对象储存到sharepreference
 *
 * @param key
 * @param device
 * @param <T>
 */
public static <T> boolean saveDeviceData(String key, T device) {
    if (mSharedPreferences == null) {
        mSharedPreferences = UiUtils.getContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {   //Device为自定义类
        // 创建对象输出流,并封装字节流
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        // 将对象写入字节流
        oos.writeObject(device);
        // 将字节流编码成base64的字符串
        String oAuth_Base64 = new String(Base64.encode(baos
                .toByteArray(), Base64.DEFAULT));
        mSharedPreferences.edit().putString(key, oAuth_Base64).commit();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 将对象从shareprerence中取出来
 *
 * @param key
 * @param <T>
 * @return
 */
public static <T> T getDeviceData(String key) {
    if (mSharedPreferences == null) {
        mSharedPreferences = UiUtils.getContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
    }
    T device = null;
    String productBase64 = mSharedPreferences.getString(key, null);

    if (productBase64 == null) {
        return null;
    }
    // 读取字节
    byte[] base64 = Base64.decode(productBase64.getBytes(), Base64.DEFAULT);

    // 封装到字节流
    ByteArrayInputStream bais = new ByteArrayInputStream(base64);
    try {
        // 再次封装
        ObjectInputStream bis = new ObjectInputStream(bais);

        // 读取对象
        device = (T) bis.readObject();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return device;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值