錯誤代碼
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;
}
關鍵修正點
onCreate **只能有一個 Bundle 參數**。
- 資料透過
Intent Extra 傳遞。
- 資料庫查詢用
? 佔位符防注入,getReadableDatabase 讀取優先。
Cursor 用完必須 close()。