SharePreferences 存储复杂类型数据

来源:互联网 发布:淘宝网电视图片及价格 编辑:程序博客网 时间:2024/05/22 05:12
  1. SharedPreferences passwd = getPreferences(Activity.MODE_PRIVATE);  
  2. SharedPreferences.Editor editor = passwd.edit();  
  3. ByteArrayOutputStream toByte = new ByteArrayOutputStream();  
  4. ObjectOutputStream oos = null;  
  5. try {  
  6.     oos = new ObjectOutputStream(toByte);  
  7. catch (IOException e) {  
  8.     // TODO Auto-generated catch block  
  9.     Log.e(TAG, e.toString());  
  10. }  
  11. if(oos != null){  
  12.     Log.e(TAG, "oos != null");  
  13.     try {  
  14.         oos.writeObject(passwords);  
  15.     } catch (IOException e) {  
  16.         // TODO Auto-generated catch block  
  17.         Log.e(TAG, e.toString());  
  18.     }  
  19. }  
  20. else  
  21. {  
  22.     Log.e(TAG, "oos == null");  
  23. }  
  24.   
  25. //对byte[]进行Base64编码  
  26. String PasswordMapBase64 = new String(Base64Coder.encode(toByte.toByteArray()));  
  27. editor.putString("KEY", PasswordMapBase64);  
  28. editor.commit();  

提取:
[java] view plaincopy
  1. SharedPreferences prefer = getPreferences(Activity.MODE_PRIVATE);  
  2. String passwordinbase64 = prefer.getString("KEY"null);  
  3. if(passwordinbase64 != null)  
  4. {  
  5.     byte[] base64Bytes = Base64Coder.decode(passwordinbase64);    
  6.     ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);    
  7.     ObjectInputStream ois = null;  
  8.     try {  
  9.         ois = new ObjectInputStream(bais);  
  10.     } catch (StreamCorruptedException e) {  
  11.         // TODO Auto-generated catch block  
  12.         Log.e("------", e.toString());  
  13.     } catch (IOException e) {  
  14.         // TODO Auto-generated catch block  
  15.         Log.e("------", e.toString());  
  16.     }    
  17.     if(ois != null)  
  18.     {  
  19.         try {  
  20.             passwords = (Map) ois.readObject();  
  21.         } catch (OptionalDataException e) {  
  22.             // TODO Auto-generated catch block  
  23.             Log.e("------", e.toString());  
  24.         } catch (ClassNotFoundException e) {  
  25.             // TODO Auto-generated catch block  
  26.             Log.e("------", e.toString());  
  27.         } catch (IOException e) {  
  28.             // TODO Auto-generated catch block  
  29.             Log.e("------", e.toString());  
  30.         }   
  31.     }  
  32. }  

其中:
[java] view plaincopy
  1. private Map<String,String> passwords = new HashMap<String,String>(); 
0 0
原创粉丝点击