入门Android开发--笔记--SharedPrefrence存储、读对象

来源:互联网 发布:英语磨耳朵软件 编辑:程序博客网 时间:2024/05/22 12:54
    public void savePerson(JSONObject json) throws JSONException{       SharedPreferences preferences = getSharedPreferences("main",Context.MODE_PRIVATE);        Person person=new Person();        Iterator it = json.keys();//创建一个遍历器        while (it.hasNext()) {            String key = (String) it.next();            String value = json.getString(key);
            //对json里的数据逐个读取,设置需要的数据
 <span style="white-space:pre"></span>    if(key.equals("userid")){                person.setUserid(value);            }            else if(key.equals("mobile")){                person.setMobile(value);            }            else if(key.equals("realname")){                person.setRealname(value);            else if(key.equals("province")){                person.setProvince(value);            }            else if(key.equals("city")){                person.setCity(value);            }            else if(key.equals("county")){                person.setCounty(value);            }            else if(key.equals("detail")){                person.setDetail(value);            }        }<span style="white-space:pre"></span>//编码        ByteArrayOutputStream baos = new ByteArrayOutputStream();        try {            ObjectOutputStream oos = new ObjectOutputStream(baos);            oos.writeObject(person);//            String productBase64 = new String(org.apache.commons.codec.binary.Base64.encodeBase64(baos                    .toByteArray()));//            SharedPreferences.Editor editor = preferences.edit();            editor.putString("person", productBase64);
            editor.apply();//commit立即提交,apply会在后台handle        } catch (IOException e) {            e.printStackTrace();        }    }<pre name="code" class="html">    public Person readPerson() {        preferences = getSharedPreferences("main",Context.MODE_PRIVATE);        Person person=new Person();        String productBase64 = preferences.getString("person", "");        if (productBase64.equals("")) {            return null;        }        byte[] base64 = Base64.decodeBase64(productBase64.getBytes());        ByteArrayInputStream bais = new ByteArrayInputStream(base64);        try {            ObjectInputStream bis = new ObjectInputStream(bais);            try {                person = (Person) bis.readObject();            } catch (ClassNotFoundException e) {                e.printStackTrace();            }        }catch (IOException e) {            e.printStackTrace();        }        return person;    }


0 0
原创粉丝点击