android 使用sharedpreferences 保存对象

需要注意的是:要保存的对象,必须实现serializable的对象

public class SharedUtil {  
    private final static String FILE_NAME = "data_save"; 
    private final static String KEY = "data";  

      /** 
       * desc:保存对象    
       * @param context 
       * @param key  
       * @param obj 
       * 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 (Exception e) {                         
          }  
      }  
      /** 
       * 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 (Exception e) {               
          }  
          //所有异常返回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;  
    } 
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中,因为 BluetoothDevice 并没有实现 Serializable 接口,所以不能直接将 BluetoothDevice 对象保存SharedPreferences 中。不过,我们可以将 BluetoothDevice 对象中的 MAC 地址和名称保存SharedPreferences 中。 以下是一个示例代码,用来将 BluetoothDevice 对象的 MAC 地址和名称保存SharedPreferences 中: ```java // 将 BluetoothDevice 对象保存SharedPreferences 中 private void saveBluetoothDevice(BluetoothDevice device) { // 获取 SharedPreferences 对象 SharedPreferences sharedPreferences = getSharedPreferences("BluetoothDeviceInfo", Context.MODE_PRIVATE); // 获取 MAC 地址和名称 String address = device.getAddress(); String name = device.getName(); // 获取 SharedPreferences 编辑器对象 SharedPreferences.Editor editor = sharedPreferences.edit(); // 保存 MAC 地址和名称 editor.putString("address", address); editor.putString("name", name); // 提交更改 editor.apply(); } ``` 在代码中,我们首先通过 getSharedPreferences() 方法获取到一个 SharedPreferences 对象,并通过 edit() 方法获取到它的编辑器对象。然后,我们通过 BluetoothDevice 对象的 getAddress() 和 getName() 方法获取到 MAC 地址和名称,并将它们保存SharedPreferences 中。最后,我们通过 apply() 方法提交更改。 在需要读取保存的 BluetoothDevice 信息时,可以通过以下代码读取: ```java // 从 SharedPreferences 中读取 BluetoothDevice 信息 private BluetoothDevice readBluetoothDevice() { // 获取 SharedPreferences 对象 SharedPreferences sharedPreferences = getSharedPreferences("BluetoothDeviceInfo", Context.MODE_PRIVATE); // 读取保存的 MAC 地址和名称 String address = sharedPreferences.getString("address", null); String name = sharedPreferences.getString("name", null); // 如果 MAC 地址或名称为空,则返回 null if (address == null || name == null) { return null; } // 使用 MAC 地址创建 BluetoothDevice 对象 BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); return bluetoothAdapter.getRemoteDevice(address); } ``` 在代码中,我们首先通过 getSharedPreferences() 方法获取到之前保存SharedPreferences 对象,并通过 getString() 方法读取保存的 MAC 地址和名称。然后,我们使用 BluetoothAdapter 的 getRemoteDevice() 方法根据 MAC 地址创建 BluetoothDevice 对象。需要注意的是,如果之前没有保存过数据,则 getString() 方法会返回 null。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值