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

Android 「on a null object reference」空指針異常排查指南

     編輯:程式設計綜合問答

異常堆疊

Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

直接原因

EditText et = (EditText) v.findViewById(R.id.number); 返回 null,隨後調用 et.getText() 拋出 NPE。

常見導致 findViewById 返回 null 的原因

  1. ID 拼寫錯誤:布局 XML 中 android:id="@+id/number" 與代碼 R.id.number 不一致(大小寫、拼寫)。
  2. View 根容器錯誤:在 Button.onClick(View v) 中,v 是被點擊的 Button,調用 v.findViewById 只會在 Button 及其子視圖中查找。若 EditText 不在 Button 內部,應使用 findViewById(R.id.number)(Activity/Fragment 根視圖)或 getView().findViewById(...)(Fragment)。
  3. 布局未正確加載:setContentView 調用錯誤布局,或 Fragment onCreateView 返回錯誤根視圖。
  4. 數據綁定/ButterKnife 未綁定:使用綁定框架時未調用 bind。

排查步驟

  1. 在 findViewById 後立即加斷點或日誌:
    EditText et = findViewById(R.id.number); // 使用正確根視圖
    Log.d("DEBUG", "et=" + et); // 為 null 則上述原因之一
    
  2. 檢查布局 XML 確認 ID 存在且唯一。
  3. 確認調用 findViewById 的上下文(Activity/Fragment/View)正確。

最佳實踐

  • 使用 ViewBinding 或 DataBinding 替代手動 findViewById,編譯期即可發現 ID 錯誤。
  • 在 onCreate/onViewCreated 中初始化視圖引用,避免在事件回調中重複查找。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved