android中通过SharedPreferences进行对象的存储

我们知道SharedPreferences只能保存简单类型的数据,例如,String、int等。如果想用SharedPreferences存取更复杂的数据类型(类、图像等),就需要对这些数据进行编码。我们通常会将复杂类型的数据转换成Base64编码,然后将转换后的数据以字符串的形式保存在 XML文件中。

  存储对象:

     AddNewWord addWord=new AddNewWord();
          addWord.setWords(word.getWords());
          addWord.setWordClass(i);
          SharedPreferences mySharedPreferences=getSharedPreferences("new_word", Activity.MODE_WORLD_READABLE);
          ByteArrayOutputStream baos = new ByteArrayOutputStream(3000);
          ObjectOutputStream oos=null;
          try {
           oos = new ObjectOutputStream(baos);
           oos.writeObject(addWord);
          } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }
          // 将Product对象放到OutputStream中
          // 将Product对象转换成byte数组,并将其进行base64编码
          String newWord = new String(Base64.encodeBase64(baos.toByteArray()));
          SharedPreferences.Editor editor = mySharedPreferences.edit();
          // 将编码后的字符串写到base64.xml文件中
          editor.putString("newWord", newWord);
          editor.commit();

读取对象:

    String wordBase64 = mySharedPreferences.getString("new_word", "");
   // 对Base64格式的字符串进行解码
       byte[] base64Bytes = Base64.decodeBase64(wordBase64 .getBytes());
         ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
      ObjectInputStream ois = new ObjectInputStream(bais);
  // 从ObjectInputStream中读取Product对象
     AddNewWord addWord= (AddNewWord ) ois.readObject();

对象实体:

 

public class AddNewWord implements Serializable{


 private static final long serialVersionUID = -37782648386953312L;
 private String words;
 private int wordClass;
 public String getWords() {
  return words;
 }
 public void setWords(String words) {
  this.words = words;
 }
 public int getWordClass() {
  return wordClass;
 }
 public void setWordClass(int wordClass) {
  this.wordClass = wordClass;
 }
 @Override
 public String toString() {
  return "AddNewWord [words=" + words
    + ", wordClass=" + wordClass
    + "]";
 }
 
}

注:Base 64是apathe的开源jar包,需要下载点击打开链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值