ITeye博客

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

zhy20045923 · 2016-04-14 16:36 · android · 移动开发 · Markdown

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。