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

Android Activity 實例化失敗:findViewById 呼叫時機早於 setContentView

     編輯:程式設計綜合問答

崩潰堆疊分析

java.lang.RuntimeException: Unable to instantiate activity ...
Caused by: java.lang.NullPointerException
    at ... NumberActivity. (findViewById 呼叫處)

成員變數初始化階段(NumberActivity 建構子隱含執行)呼叫 findViewById,但此時 **View 階層尚未建立**(setContentView 尚未執行),返回 null,後續 solve.setOnClickListener 導致 NPE。

修正:移至 onCreate 的 setContentView 之後

public class NumberActivity extends Activity {
    EditText pressure, temperature, volume;
    TextView answer;
    Button solve;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number); // 先建立 View 階層

        // 再綁定 View
        pressure = findViewById(R.id.editTextPressure);
        temperature = findViewById(R.id.editTextTemperature);
        volume = findViewById(R.id.editTextVolume);
        answer = findViewById(R.id.textViewSolve);
        solve = findViewById(R.id.buttonSolve);

        solve.setOnClickListener(v -> {
            // 解析與計算邏輯...
        });
    }
}

補充:ViewBinding / DataBinding 避免手動 findViewById

// build.gradle
viewBinding { enabled = true }

// Activity
private ActivityNumberBinding binding;
@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = ActivityNumberBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    binding.buttonSolve.setOnClickListener(v -> {
        double p = Double.parseDouble(binding.editTextPressure.getText().toString());
        // ...
    });
}

編譯期生成綁定類,類型安全、無 NPE、程式碼更簡潔。

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