在 ListView 的 OnItemClickListener 中獲取項目數據並通過 Intent 傳遞給下一個 Activity,接收方調用 setText() 時拋出 NullPointerException。
title、desc 已到達)。TextView 未正確初始化:可能 findViewById 使用錯誤 ID,或布局文件與代碼不匹配。setContentView 之後調用 findViewById。// 接收 Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail); // 確保布局正確
TextView tvTitle = findViewById(R.id.tv_title); // ID 必須與 XML 一致
TextView tvDesc = findViewById(R.id.tv_desc);
Intent intent = getIntent();
if (intent != null) {
String title = intent.getStringExtra("title");
String desc = intent.getStringExtra("desc");
if (tvTitle != null) tvTitle.setText(title);
if (tvDesc != null) tvDesc.setText(desc);
}
}
使用 Log.d 或斷點確認 tvTitle、tvDesc 是否為 null;若為 null,檢查布局 XML 中的 android:id 屬性。