1. 程式人生 > >Android SharedPreferences儲存和讀取物件

Android SharedPreferences儲存和讀取物件

SharedPreferences儲存和讀取物件

1.首先要序列化物件(下面是序列化實體類的例子,不方便貼出實體類所有的程式碼)

public class LoginResult extends BaseResult implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private String mobiletoken;

2.儲存和讀取物件的封裝

public class ObjectSaveUtil {
	
	private final static String FILENAME = "login_data_save";
	
	private final static String KEY = "loginResult";
	
	  /**
	   * desc:儲存物件	 
	   * @param context
	   * @param key 
	   * @param obj 要儲存的物件,只能儲存實現了serializable的物件
	   * modified:	
	   */
	  public static void saveObject(Context context,Object obj){
	      try {
	          // 儲存物件
	          SharedPreferences.Editor sharedata = context.getSharedPreferences(FILENAME, 0).edit();
	          //先將序列化結果寫到byte快取中,其實就分配一個記憶體空間
	          ByteArrayOutputStream bos=new ByteArrayOutputStream();
	          ObjectOutputStream os=new ObjectOutputStream(bos);
	          //將物件序列化寫入byte快取
	          os.writeObject(obj);
	          //將序列化的資料轉為16進位制儲存
	          String bytesToHexString = bytesToHexString(bos.toByteArray());
	          //儲存該16進位制陣列
	          sharedata.putString(KEY, bytesToHexString);
	          sharedata.commit();
	      } catch (IOException e) {
	          e.printStackTrace();
	          Log.e("", "儲存obj失敗");
	      }
	  }
	  /**
	   * desc:將陣列轉為16進位制
	   * @param bArray
	   * @return
	   * modified:	
	   */
	  public static String bytesToHexString(byte[] bArray) {
	      if(bArray == null){
	          return null;
	      }
	      if(bArray.length == 0){
	          return "";
	      }
	      StringBuffer sb = new StringBuffer(bArray.length);
	      String sTemp;
	      for (int i = 0; i < bArray.length; i++) {
	          sTemp = Integer.toHexString(0xFF & bArray[i]);
	          if (sTemp.length() < 2)
	              sb.append(0);
	          sb.append(sTemp.toUpperCase());
	      }
	      return sb.toString();
	  }
	  /**
	   * desc:獲取儲存的Object物件
	   * @param context
	   * @param key
	   * @return
	   * modified:	
	   */
	  public static Object readObject(Context context){
	      try {
	          SharedPreferences sharedata = context.getSharedPreferences(FILENAME, 0);
	          if (sharedata.contains(KEY)) {
	               String string = sharedata.getString(KEY, "");
	               if(TextUtils.isEmpty(string)){
	                   return null;
	               }else{
	                   //將16進位制的資料轉為陣列,準備反序列化
	                   byte[] stringToBytes = StringToBytes(string);
	                     ByteArrayInputStream bis=new ByteArrayInputStream(stringToBytes);
	                     ObjectInputStream is=new ObjectInputStream(bis);
	                     //返回反序列化得到的物件
	                     Object readObject = is.readObject();
	                     return readObject;
	               }
	          }
	      } catch (StreamCorruptedException e) {
	          // TODO Auto-generated catch block
	          e.printStackTrace();
	      } catch (IOException e) {
	          // TODO Auto-generated catch block
	          e.printStackTrace();
	      } catch (ClassNotFoundException e) {
	          // TODO Auto-generated catch block
	          e.printStackTrace();
	      }
	      //所有異常返回null
	      return null;
	      
	  }
	  /**
	   * desc:將16進位制的資料轉為陣列
	   * <p>建立人:聶旭陽 , 2014-5-25 上午11:08:33</p>
	   * @param data
	   * @return
	   * modified:	
	   */
	  public static byte[] StringToBytes(String data){
	      String hexString=data.toUpperCase().trim();
	      if (hexString.length()%2!=0) {
	          return null;
	      }
	      byte[] retData=new byte[hexString.length()/2];
	      for(int i=0;i<hexString.length();i++)
	      {
	          int int_ch;  // 兩位16進位制數轉化後的10進位制數
	          char hex_char1 = hexString.charAt(i); ////兩位16進位制數中的第一位(高位*16)
	          int int_ch3;
	          if(hex_char1 >= '0' && hex_char1 <='9')
	              int_ch3 = (hex_char1-48)*16;   //// 0 的Ascll - 48
	          else if(hex_char1 >= 'A' && hex_char1 <='F')
	              int_ch3 = (hex_char1-55)*16; //// A 的Ascll - 65
	          else
	              return null;
	          i++;
	          char hex_char2 = hexString.charAt(i); ///兩位16進位制數中的第二位(低位)
	          int int_ch4;
	          if(hex_char2 >= '0' && hex_char2 <='9')
	              int_ch4 = (hex_char2-48); //// 0 的Ascll - 48
	          else if(hex_char2 >= 'A' && hex_char2 <='F')
	              int_ch4 = hex_char2-55; //// A 的Ascll - 65
	          else
	              return null;
	          int_ch = int_ch3+int_ch4;
	          retData[i/2]=(byte) int_ch;//將轉化後的數放入Byte裡
	      }
	      return retData;
	}
	
}

挺好用的,歡迎大家複製使用