`
zhy20045923
  • 浏览: 153377 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

[转载]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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics