android_巧用SharedPrefrences储存ArrayList等Collection的实现类

/**
 * collection 里的类必须要implements Serializable,因为ObjectOutputStream的缘故
 */
public class SPUtils {
    public static final String SP_NAME="needYourName";//您的SharedPreferences的名字
    public static void setSPCollection(Context context, Collection collection, String collectionName) throws IOException {
        SharedPreferences.Editor edit=getSharedPreferences(context, SP_NAME).edit();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(collection);
        String string = new String(Base64.encode(byteArrayOutputStream.toByteArray(), Base64.DEFAULT));//利用Base64防止乱码
        edit.putString(collectionName,string);
        edit.apply();
        objectOutputStream.close();
    }
    public static Collection getSPCollection(Context context, String collectionName) throws IOException, ClassNotFoundException {
        String string = getSharedPreferences(context, SP_NAME).getString(collectionName, "");
        if (TextUtils.isEmpty(string)||TextUtils.isEmpty(string.trim())){
            return null;
        }
        byte[] decodeBytes = Base64.decode(string.getBytes(), Base64.DEFAULT);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decodeBytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Collection collection = (Collection) objectInputStream.readObject();
        objectInputStream.close();
        return collection;
    }
    public static SharedPreferences getSharedPreferences(Context context,String spName){
        return context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    }
}

不懂可以提问,但或许度娘更适合你呢,开个玩笑,今天是大年初一,还敲代码,我也是醉了,实在是无聊的慌呀。
也记录一下,20岁快结束了,好好努力,加油。

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值