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

Android Handler 更新 UI 崩潰:findViewById ID 錯誤導致 View 為 null

     編輯:程式設計綜合問答

錯誤現象

Handler 中 ReturnShow.setText(...) 拋出 NPE,Logcat 顯示 ReturnShow 為 null。

根本原因

ReturnShow = (EditText) findViewById(R.id.ResultShow); // ID 寫錯:應為 R.id.ReturnShow

XML 中 EditText 的 android:id="@+id/ReturnShow",但程式碼找 R.id.ResultShow,導致 findViewById 回傳 null。

修正

ReturnShow = (EditText) findViewById(R.id.ReturnShow); // 對應 XML id

Handler 執行緒安全補充

原始碼中 mHandler.handleMessage(msg) 直接呼叫,會在背景執行緒執行 UI 操作導致 CalledFromWrongThreadException。正確做法:

// 背景執行緒
mHandler.sendEmptyMessage(0x123); // 或 sendMessage

// Handler 定義在 UI 執行緒(Activity onCreate 中),自動關聯主 Looper
Handler mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message msg) {
        // 此處安全更新 UI
        ReturnShow.setText(sMsg);
    }
};

檢查清單

  • XML id 與 findViewById 參數完全一致
  • View 初始化在 setContentView 之後
  • Handler 建立於主執行緒,或傳入 Looper.getMainLooper()
  • 背景執行緒用 sendMessage 而非直接 handleMessage
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved