Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 SharedPreferences 儲存 Java 物件:序列化與還原完整實作

編輯:關於 Android 程式設計

SharedPreferences 天生只處理 String、int、boolean 這類基本型別,但只要繞個彎,就能用來保存整個自訂物件。核心思路只有一句話:把物件序列化成位元組,再轉成 16 進位字串塞進 SharedPreferences。

實作步驟

1. 要保存的類別必須實作 Serializable 介面。

2. 把序列化後的位元組陣列轉為 16 進位字串,再寫入 SharedPreferences。

3. 讀取時反向操作:把 16 進位字串還原為位元組陣列,再反序列化回物件。

步驟一:讓類別可序列化

public class Sertest implements Serializable {
    private String name;
    private int age;
}

步驟二與步驟三:完整工具類

以下四個方法構成一個閉環:saveObject 負責寫入,readObject 負責讀出,中間由 bytesToHexString 與 StringToBytes 負責格式轉換。

/**
 * 保存物件到 SharedPreferences
 * @param obj 只能保存實作了 Serializable 的物件
 */
public static void saveObject(Context context, String key, Object obj) {
    try {
        SharedPreferences.Editor sharedata = context.getSharedPreferences(FILENAME, 0).edit();
        // 先把序列化結果寫進 byte 緩衝區(實質上是配置一塊記憶體空間)
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(bos);
        os.writeObject(obj); // 序列化並寫入緩衝區
        // 把序列化資料轉成 16 進位字串
        String bytesToHexString = bytesToHexString(bos.toByteArray());
        sharedata.putString(key, bytesToHexString);
        sharedata.commit();
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("", "保存obj失敗");
    }
}

/**
 * 將位元組陣列轉為 16 進位字串
 */
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();
}

/**
 * 讀出並還原物件
 */
public Object readObject(Context context, String key) {
    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);
                return is.readObject();
            }
        }
    } catch (StreamCorruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    // 任何例外都回傳 null
    return null;
}

/**
 * 將 16 進位字串轉為位元組陣列
 */
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 進位數的第一位(高位 × 16)
        char hex_char1 = hexString.charAt(i);
        int int_ch1;
        if (hex_char1 >= '0' && hex_char1 <= '9') {
            int_ch1 = (hex_char1 - 48) * 16;
        } else if (hex_char1 >= 'A' && hex_char1 <= 'F') {
            int_ch1 = (hex_char1 - 55) * 16;
        } else {
            return null;
        }
        i++;
        char hex_char2 = hexString.charAt(i); // 第二位(低位)
        int int_ch2;
        if (hex_char2 >= '0' && hex_char2 <= '9') {
            int_ch2 = (hex_char2 - 48);
        } else if (hex_char2 >= 'A' && hex_char2 <= 'F') {
            int_ch2 = hex_char2 - 55;
        } else {
            return null;
        }
        int_ch = int_ch1 + int_ch2;
        retData[i / 2] = (byte) int_ch;
    }
    return retData;
}

實務提醒

這種做法本質上是把物件攤平成字串,因此只適合資料量小的情境,例如保存一份使用者設定或登入資訊。若要保存大量結構化資料,改用資料庫或檔案會更合適。另外,Serializable 類別一旦修改欄位結構,舊資料反序列化時可能失敗,記得在 readObject 的例外處理中預留退路。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved