《第一行代碼》第 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
<Button
android:id="@+id/sendRequest"
android:text="發送請求" />
<TextView
android:id="@+id/responseText"
android:text="響應結果" />
MainActivity.java:45)。findViewById、Intent extras、Bundle 等)。R.id.xxx 與 XML android:id="@+id/xxx" **完全一致**,且類型匹配(Button 對 Button,TextView 對 TextView)。R.id.xxx,彈出預覽可見對應 XML 元素與類型。new Thread。Handler 傳遞結果。AndroidManifest.xml 需 <uses-permission android:name="android.permission.INTERNET"/>。res/xml/network_security_config.xml 配置 cleartextTrafficPermitted="true" 或改用 HTTPS。OkHttp / Retrofit / Volley,簡化代碼、自動處理連接池、緩存、取消請求。**閃退 90% 是綁定錯誤或空指針,冷靜對照 ID 與類型即可快速定位。**