應用崩潰,Logcat 顯示:
java.lang.NullPointerException: Attempt to invoke virtual method '...' on a null object reference
view.findViewById。getStringExtra("key") 返回 null 直接調用方法。onCreateView 前訪問 View、onDestroy 後仍持有引用。textView.setText()。// 1. View 綁定
TextView tv = findViewById(R.id.tv_name);
if (tv != null) tv.setText(name);
// 2. Bundle 取值
String value = getIntent().getStringExtra("key");
if (value != null) { /* 使用 */ }
// 3. 異步回調中檢查 Activity 存活
if (!isFinishing() && !isDestroyed()) {
runOnUiThread(() -> tv.setText(data));
}
// 4. 使用 ?. 操作符(Kotlin)或 Objects.requireNonNull(Java)
CSDN 經典排查指南:Android 空指針異常系統性排查
NPE 是 Android 開發第一大崩潰源,核心對策:假設一切可為 null,用前必判,生命周期感知,善用工具定位。