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

Android HttpURLConnection 閃退排查:findViewById 綁定錯誤導致空指針

     編輯:程式設計疑難解答

異常現場

《第一行代碼》第 10 章網絡請求示例運行閃退,日志顯示 NullPointerException 或類似崩潰。

根因定位

**onCreate 中 findViewById 綁定錯誤**,導致 Button 持有 TextView 的引用(或相反),後續調用 button.setOnClickListener 時實際操作的是 TextView,或 textView.setText 時操作 Button,引發類轉換異常/空指針。

錯誤代碼對比

// 錯誤版
textView = (TextView) findViewById(R.id.sendRequest); // 實際是 Button 的 id
button = (Button) findViewById(R.id.responseText);    // 實際是 TextView 的 id

// 正確版
textView = (TextView) findViewById(R.id.responseText); // 對應 layout 中 TextView 的 id
button = (Button) findViewById(R.id.sendRequest);      // 對應 layout 中 Button 的 id

XML 佈局對照(fragment_main.xml)

<Button
    android:id="@+id/sendRequest"
    android:text="發送請求" />

<TextView
    android:id="@+id/responseText"
    android:text="響應結果" />

通用排查步驟

  1. **閱讀崩潰日志**:定位異常行號(如 MainActivity.java:45)。
  2. **對照該行代碼**:檢查變量賦值來源(findViewById、Intent extras、Bundle 等)。
  3. **核對 XML id**:確保 Java 代碼中 R.id.xxx 與 XML android:id="@+id/xxx" **完全一致**,且類型匹配(Button 對 Button,TextView 對 TextView)。
  4. **善用 Android Studio**:將滑鼠懸停於 R.id.xxx,彈出預覽可見對應 XML 元素與類型。

網絡請求最佳實踐補充

  • **子線程請求** ✅ 示例正確使用 new Thread。
  • **Handler 更新 UI** ✅ 示例正確使用 Handler 傳遞結果。
  • **權限聲明** ⚠️ AndroidManifest.xml 需 <uses-permission android:name="android.permission.INTERNET"/>。
  • **明文流量** ⚠️ Android 9+ (API 28+) 默認禁止 HTTP,需在 res/xml/network_security_config.xml 配置 cleartextTrafficPermitted="true" 或改用 HTTPS。
  • **現代替代** 建議遷移至 OkHttp / Retrofit / Volley,簡化代碼、自動處理連接池、緩存、取消請求。

**閃退 90% 是綁定錯誤或空指針,冷靜對照 ID 與類型即可快速定位。**

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