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
原始碼中 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);
}
};
findViewById 參數完全一致setContentView 之後Looper.getMainLooper()sendMessage 而非直接 handleMessage