首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android Studio SQLite 查詢傳值報錯:Activity onCreate 參數錯誤導致崩潰

     編輯:程式設計疑難解答

錯誤代碼


public class Detailed extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState, SQLiteHelper msh, int pointId) { // ❌ 參數錯誤
        // ...
    }
}

原因:Activity 生命週期方法簽名固定,不可自行增加參數

  • 系統只會呼叫 onCreate(Bundle)。
  • 額外參數導致方法永不被調用,msh、pointId 為 null/0,後續查詢崩潰。

修正:標準 onCreate + Intent 取得參數


public class Detailed extends Activity {
    private SQLiteHelper msh;
    private int pointId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.self_layout);

        // 1. 從 Intent 取得參數
        pointId = getIntent().getIntExtra("pointId", -1);
        msh = new SQLiteHelper(this); // 或單例獲取

        // 2. 初始化 View
        img = findViewById(R.id.vr);
        lng = findViewById(R.id.lngText);

        // 3. 查詢並顯示
        if (pointId != -1) {
            Point point = SQLiteHelper.getDetailedById(msh, pointId);
            if (point != null) lng.setText(String.valueOf(point.getLng()));
        }

        img.setOnClickListener(v -> {
            startActivity(new Intent(this, PanoramaActivity.class));
        });
    }
}

SQLiteHelper 靜態查詢方法修正


public static Point getDetailedById(SQLiteHelper helper, int pointId) {
    SQLiteDatabase db = helper.getReadableDatabase(); // 唯讀足夠
    Cursor cursor = db.rawQuery(
        "SELECT lng,lat,direction,uniformity,temperature,dustproof,material,metope,door,illumination,type " +
        "FROM vr_point WHERE pointID = ?", new String[]{String.valueOf(pointId)});

    Point po = null;
    if (cursor.moveToFirst()) {
        po = new Point();
        po.setLng(cursor.getDouble(0));
        po.setLat(cursor.getDouble(1));
        po.setDirection(cursor.getString(2));
        // ... 其他欄位
    }
    cursor.close();
    return po;
}

關鍵修正點

  1. onCreate **只能有一個 Bundle 參數**。
  2. 資料透過 Intent Extra 傳遞。
  3. 資料庫查詢用 ? 佔位符防注入,getReadableDatabase 讀取優先。
  4. Cursor 用完必須 close()。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved