专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > 移动开发

[转载]SharedPreferences 储存java对象,很实用

发布时间:2010-05-29 22:43:36 文章来源:www.iduyao.cn 采编人员:星星草
[转载]SharedPreferences 存储java对象,很实用
public void putObject(String key , Object obj){
               
                ByteArrayOutputStream bos = null;
                ObjectOutputStream oos = null;
                try {
                        bos = new ByteArrayOutputStream();
                        oos = new ObjectOutputStream(bos);
                        oos.writeObject(obj);
                        String serStr = bos.toString("ISO-8859-1");
                        serStr = URLEncoder.encode(serStr, "UTF-8");
                        editer.putString(key, serStr);
                        editer.commit();
                       
                } catch (IOException e) {
                        e.printStackTrace();
                }finally{
                        try {
                                oos.close();
                                bos.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
        }
       
        public Object getObject(String key){
               
                String serStr = preferences.getString(key, "");
                ByteArrayInputStream bai = null;
                ObjectInputStream ois = null;
                Object object = null;
                if(serStr != ""){
                       
                        try {
                                String sedStr = URLDecoder.decode(serStr, "UTF-8");
                                bai = new ByteArrayInputStream(sedStr.getBytes("ISO-8859-1"));
                                ois = new ObjectInputStream(bai);
                                object = ois.readObject();
                               
                        } catch (Exception e) {
                                e.printStackTrace();
                        }finally{
                                try {
                                        ois.close();
                                        bai.close();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }
               
               
                return object;
        }
序列化实体的话,别忘了 implements Serializable


原帖地址:
http://www.eoeandroid.com/thread-902119-1-6.html
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: