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

Android Button.setOnClickListener 導致 Unable to start Activity:找不到 View 的排查步驟

     編輯:程式設計疑難解答

錯誤現象

App 啟動崩潰,Logcat 提示:

java.lang.RuntimeException: Unable to start activity ComponentInfo{...}:
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.Button.setOnClickListener(...)' on a null object reference

根本原因

findViewById(R.id.button1) 回傳 null,原因通常是:

  1. Layout XML 中沒有 id 為 button1 的 Button(拼寫錯誤、或屬於其他 layout)。
  2. setContentView 載入的 layout 檔案錯誤(如載入 activity_main.xml 但按鈕在 fragment_main.xml)。
  3. Fragment 中未在 onCreateView 內 findViewById,直接在 Activity 的 onCreate 呼叫。

快速排查清單

  1. 打開 res/layout/activity_main.xml,確認 <Button android:id="@+id/button1" /> 存在。
  2. 確認 setContentView(R.layout.activity_main) 與 layout 檔名一致。
  3. 若使用 Fragment,將初始化移至 onViewCreated 或 onCreateView 內,並用 view.findViewById(...)。
  4. Clean Project → Rebuild,排除 R 檔不同步問題。

最佳實踐:ViewBinding / DataBinding

啟用 viewBinding true 後,編譯器產生型別安全的綁定類,編譯期即可發現找不到 View 的錯誤,徹底杜絕 NullPointerException。

// build.gradle
android {
    viewBinding {
        enabled = true
    }
}

// Activity
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    binding.button1.setOnClickListener(v -> { ... }); // 型別安全,不會為 null
}

總結

90% 的 Unable to start activity + NullPointerException on Button 都是「Layout 與 Java 程式碼的 ID 不對應」。善用 ViewBinding 可從根源消除此類低級錯誤。

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