編輯:關於 Android 程式設計
需要把一批自訂資料(例如使用者清單)持久化到裝置上時,Java 原生的序列化機制是最省事的方案。實作起來只要三個要素:資料類別實作 Serializable、一組 ObjectOutputStream、以及一個檔案。
兩者常被混用,但適用場景不同:
package cc.test.serializable;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id;
private String name;
// 強烈建議明確定義版本序號
public static final long serialVersionUID = 9527L;
public Student() { super(); }
public Student(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
// getter / setter / toString 略
}
serialVersionUID 千萬別省略。一旦類別結構在版本更新中改變,而這個值又沒有固定下來,反序列化時就會直接丟 InvalidClassException,舊資料全部讀不回來。
File file = new File(Environment.getExternalStorageDirectory().toString()
+ File.separator + "Test" + File.separator + "data.dat");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
// 寫入
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentsArrayList);
oos.close();
fos.close();
// 讀出
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Student> saved = (ArrayList<Student>) ois.readObject();
ois.close();
fis.close();
注意 ArrayList 本身已經實作 Serializable,所以只要元素型別也實作了,整個清單就能一次寫入,不必自己逐筆處理。另外檔案寫在子目錄底下時,一定要先把父目錄建出來,這是最常見的 IOException 來源。
第一,收尾一定要用 try/finally 或 try-with-resources 確保串流被關掉,否則檔案會殘留不完整內容,下次讀取就炸。
第二,寫入建議採「先寫暫存檔、完成後再改名覆蓋」的策略。序列化檔案一旦寫到一半被中斷(例如通話來電、低電壓關機),檔案通常就報廢了。
第三,從 Android 6.0 開始,存取外部儲存空間需要 READ/WRITE_EXTERNAL_STORAGE 執行期授權;如果不想處理權限,改用 getFilesDir() 存到應用私有目錄會乾淨許多。
版面部分完全不需要額外元件,一個 TextView 就足夠驗證:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
Android 在 Activity 之間傳遞圖片(Bitmap)的方法
Activity 之間傳遞參數是日常開發的基本功,用 Intent.putExtra() 傳字串、傳數字都很直覺。但如果要傳的是一張圖片呢?關鍵在於 Bitmap 已經實
Android 自定義 View:實作字母導航欄
在聯絡人、音樂或相簿等應用中,字母導航欄是很常見的輔助操作。本文將說明如何透過自定義 View,實作一個可滑動、可高亮、可與 ListView 聯動的字母索引欄。 自定
OkHttp 源碼完全解析:從 Request 到連接池
OkHttp 是目前 Android 上最受歡迎的網路庫之一。本文將帶你深入源碼,理清 OkHttp 的核心架構:如何從構造 Request、初始化 OkHttpClie
Android 6.0 運行時權限封裝:EasyPermissionUtil 設計思路
背景:權限模型為什麼變了 從 Android 6.0(API 23)開始,權限申請由「安裝時一次性列出」改為「運行時動態申請」。危險級別的權限要在真正用到相關功能時才向使