SharedPreferences保存对象

Android提供的SharedPreferences本地存储功能,本人觉得这个方便,而且操作简单,但是却只能保存字符串,有时我们需要存储对象。我们需要将对象通过SharedPreferences保存到本地,首先将对象转为字符串。


实现代码:

package com.zero.legwork.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.zero.legwork.service.GetLocationService;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

/**
 * Created by Jin_ on 2015/10/22.
 */
public class SharedPreferencesUtils {

    private final static String PREFERENCES_NAME = "LOCATION_INFO";

    public static void saveObject(Context context, String key, Object obj) {

        ByteArrayOutputStream bos = null;
        ObjectOutputStream os = null;

        try {
            SharedPreferences.Editor sharedata = context.getSharedPreferences(PREFERENCES_NAME, 0).edit();

            //先将序列化结果写到byte缓存中,其实就分配一个内存空间
            bos = new ByteArrayOutputStream();
            os = new ObjectOutputStream(bos);

            //将对象序列化写入byte缓存
            os.writeObject(obj);

            //将序列化的数据转为16进制保存
            String bytesToHexString = bytesToHexString(bos.toByteArray());

            //保存该16进制数组
            sharedata.putString(key, bytesToHexString);
            sharedata.commit();

            Log.i(GetLocationService.SAVE_LOCATION, "保存成功");

        } catch (IOException e) {
            e.printStackTrace();
            Log.e("", "保存失败");
        } finally {
            try {
                os.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Object getObject(Context context, String key) {

        ByteArrayInputStream bis = null;
        ObjectInputStream is = null;

        try {
            SharedPreferences sharedata = context.getSharedPreferences(PREFERENCES_NAME, 0);
            if (sharedata.contains(key)) {
                String string = sharedata.getString(key, "");
                if (TextUtils.isEmpty(string)) {
                    return null;
                } else {
                    //将16进制的数据转为数组,准备反序列化
                    byte[] stringToBytes = StringToBytes(string);
                    bis = new ByteArrayInputStream(stringToBytes);
                    is = new ObjectInputStream(bis);

                    //返回反序列化得到的对象
                    Object readObject = is.readObject();
                    return readObject;
                }
            }
        } catch (StreamCorruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

            try {
                is.close();
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //所有异常返回null
        return null;

    }

    public static String bytesToHexString(byte[] bArray) {
        if (bArray == null) {
            return null;
        }
        if (bArray.length == 0) {
            return "";
        }
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] StringToBytes(String data) {
        String hexString = data.toUpperCase().trim();
        if (hexString.length() % 2 != 0) {
            return null;
        }
        byte[] retData = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i++) {
            int int_ch;  // 两位16进制数转化后的10进制数
            char hex_char1 = hexString.charAt(i); 两位16进制数中的第一位(高位*16)
            int int_ch1;
            if (hex_char1 >= '0' && hex_char1 <= '9')
                int_ch1 = (hex_char1 - 48) * 16;    0 的Ascll - 48
            else if (hex_char1 >= 'A' && hex_char1 <= 'F')
                int_ch1 = (hex_char1 - 55) * 16;  A 的Ascll - 65
            else
                return null;
            i++;
            char hex_char2 = hexString.charAt(i); ///两位16进制数中的第二位(低位)
            int int_ch2;
            if (hex_char2 >= '0' && hex_char2 <= '9')
                int_ch2 = (hex_char2 - 48);  0 的Ascll - 48
            else if (hex_char2 >= 'A' && hex_char2 <= 'F')
                int_ch2 = hex_char2 - 55;  A 的Ascll - 65
            else
                return null;
            int_ch = int_ch1 + int_ch2;
            retData[i / 2] = (byte) int_ch;//将转化后的数放入Byte里
        }
        return retData;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值