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

Android TextView setText 報 NullPointerException 的經典原因與修正

     編輯:程式設計綜合問答

錯誤現場


public class MainActivity extends Activity {
    private TextView tx1;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tx1 = (TextView) findViewById(R.id.txtexample); // 這裡返回 null
        
        try {
            tx1.setText("Hello testing"); // NPE
        } catch (Exception e) { ... }
    }
}

XML 佈局錯誤


<TextView 
    android:name="@+id/txtexample"  <-- 錯誤屬性
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

根本原因

android:name 不是標準屬性,系統不識別,導致 findViewById(R.id.txtexample) 找不到 View,返回 null。

修正方法


<TextView 
    android:id="@+id/txtexample"  <-- 正確屬性
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

同類常見錯誤清單

錯誤寫法正確寫法說明
android:name="@+id/xxx"android:id="@+id/xxx"id 定義
android:id="@id/xxx"android:id="@+id/xxx"+ 表示新建 ID
findViewById(R.id.xxx) 在 setContentView 前在 setContentView 後View 未加載
Fragment 中用 getActivity().findViewByIdview.findViewById作用域錯誤
佈局文件名與 setContentView 不符檢查 R.layout.xxx資源引用錯誤

防錯最佳實踐

  1. 啟用 ViewBinding(推薦):buildFeatures { viewBinding true },編譯期檢查,消除 findViewById
  2. 或用 DataBinding:雙向綁定,更強大
  3. 保留 findViewById 時:加非空斷言 TextView tx1 = findViewById(R.id.txtexample); if (tx1 == null) throw new IllegalStateException("View not found");
  4. 佈局預覽檢查:AS Design 視圖確認 ID 正確顯示

總結

90% 的 findViewById 返回 null 都是 XML 屬性寫錯或調用時機錯。改用 ViewBinding 可從根源杜絕此類低級錯誤,提升開發效率。

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