萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 開發易錯點總結:Cursor、組件註冊、Parcelable 避坑指南

一、Cursor 操作五大雷區

  1. 未判空直接使用: query() 可能返回 null(如表不存在、權限不足),直接調用方法會拋 NPE。必須先判空。
  2. 未檢查是否為空集合: cursor.getCount() == 0 時調用 moveToFirst() 返回 false,後續讀取會出錯。判斷邏輯: if (cursor != null && cursor.moveToFirst()) { ... }。
  3. 遍歷前未移動到首行: 游標初始位置在 -1,必須先 moveToFirst() 再循環 moveToNext()。
  4. 未關閉 Cursor: 導致內存洩漏、文件句柄耗盡。使用 try-finally 或 Kotlin use/execute 延展函數確保關閉。
  5. 類型獲取不匹配: SQLite 無 Boolean 類型(存 0/1),getInt() 讀取後需轉換;Long/Int 混用需注意範圍。

二、組件未在 Manifest 註冊

  • Activity/Service/Receiver/Provider 均需在 <application> 下聲明。
  • 跨包名 Service: 若 Service 在獨立包名,需在聲明中指定完整包名:android:name="com.other.package.MyService",或在 Manifest 根節點設置 package="com.main.package" 並用相對路徑 android:name=".MyService"。
  • 隱式 Intent 啟動: 需添加 <intent-filter> 匹配 Action/Category/Data。

三、Parcelable 實現陷阱

public class MyData implements Parcelable {
    private Bitmap bitmap; // 非 Parcelable 類型!
    private String name;
    private int id;

    // 錯誤寫法:直接 writeValue(bitmap) 會崩潰(Bitmap 未實現 Parcelable)
    // 正確寫法:
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(id);
        // Bitmap 需轉 byte[] 或單獨處理
        if (bitmap != null) {
            dest.writeByte((byte) 1);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            dest.writeByteArray(stream.toByteArray());
        } else {
            dest.writeByte((byte) 0);
        }
    }

    // 讀取時對應順序讀取
    protected MyData(Parcel in) {
        name = in.readString();
        id = in.readInt();
        if (in.readByte() == 1) {
            byte[] bytes = in.createByteArray();
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        }
    }
    // ... CREATOR 實現
}

核心原則: 只能寫入基本類型、String、Parcelable、Serializable、List/Array 等系統支援類型。自定義對象必須實現 Parcelable;非 Parcelable 對象(如 Bitmap、Drawable、Connection)需轉換為字節數組或拆解基礎字段存儲。

其他高頻易錯點

  • Context 洩漏: 靜態變量持有 Activity/Context、非靜態內部類、未取消的 Handler 消息/線程。
  • 主線程耗時操作: 網絡、DB、文件 I/O、複雜計算必須放入子線程。
  • 資源未釋放: Bitmap.recycle()、Cursor.close()、FileInputStream.close()、註冊/取消註冊不成對。
  • 硬編碼尺寸/顏色: 應使用 dimens.xml、colors.xml、styles.xml 適配多螢幕。
  • 忽略配置變更重建: 横豎屏切換導致 Activity 重建,ViewModel/LiveData/onSaveInstanceState 保持數據。
copyright © 萬盛學電腦網 all rights reserved