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

Android Activity 跳轉傳值崩潰排查:getIntent().getExtras() 空指針異常

     編輯:程式設計疑難解答

崩潰現象

從 Activity A 跳轉到 Activity B 並攜帶數據,B 中調用 getIntent().getExtras() 後直接訪問 Bundle 內鍵值,導致 NullPointerException,App 崩潰。

常見原因與修正

1. 意圖中未放入 Extra

// A 中 ❌ 忘記 putExtra
Intent intent = new Intent(A.this, B.class);
startActivity(intent);

// A 中 ✅ 正確
Intent intent = new Intent(A.this, B.class);
intent.putExtra("key", "value"); // 或 putExtras(bundle)
startActivity(intent);

2. 接收端未做空判斷

// B 中 ❌ 直接訪問
Bundle bundle = getIntent().getExtras();
String val = bundle.getString("key"); // bundle 可能為 null

// B 中 ✅ 防空
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    String val = bundle.getString("key", "default");
} else {
    // 處理無數據情況:彈窗提示、finish()、跳轉回上一頁
}

3. 啟動模式導致 Intent 復用

若 B 設置了 android:launchMode="singleTop" 或 singleTask,再次啟動時走 onNewIntent(Intent),**需在該方法中更新 Intent 引用**:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent); // 關鍵:更新 getIntent() 返回值
    // 這裡處理新數據
}

調試技巧

  1. 完整堆棧截圖:崩潰日志第 8 行提示 NullPointerException,雙擊定位到具體行號。
  2. Log 打印 Intent:Log.d("Intent", "Extras: " + getIntent().getExtras()); 觀察是否為 null。
  3. 檢查目標 Activity 聲明:Manifest 中是否註冊、名稱拼寫正確、是否誤加 android:exported="false" 導致隱式啟動失敗。

最佳實踐封裝

// 基類 Activity
protected Bundle getSafeExtras() {
    Bundle b = getIntent().getExtras();
    return b != null ? b : new Bundle();
}

// 子類使用
String name = getSafeExtras().getString("name", "");
int age = getSafeExtras().getInt("age", -1);

崩潰日志1 崩潰日志2 代碼截圖1 代碼截圖2

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved