为什么我会收到此错误 - RunTimeException:无法实例化活动?

时间:2013-03-15 01:21:05

标签: android

我的LogCat说:

java.lang.RunTimeException: Unable to instantiate activity ComponentInfo{com.erikbalen.idealgaslawcalculator/com.erikbalen.idealgaslawcalculator.NumberActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity{ActivityThread.java:2121}

这是我的java文件:

public class NumberActivity extends Activity {

EditText pressure = (EditText) findViewById(R.id.editTextPressure);
EditText temperature = (EditText) findViewById(R.id.editTextTemperature);
EditText volume = (EditText) findViewById(R.id.editTextVolume);
TextView answer = (TextView) findViewById(R.id.textViewSolve);
Button solve = (Button) findViewById(R.id.buttonSolve);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_number);
    solve.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            double pressureValue = Double.parseDouble(pressure.getText().toString());
            double temperatureValue = Double.parseDouble(temperature.getText().toString());
            double volumeValue = Double.parseDouble(volume.getText().toString());
            double r = 0.0821;
            double answerValue = (pressureValue*volumeValue)/(r*temperatureValue);
            answer.setText(Double.toString(answerValue));
        }
    });
}

}

希望这就是你所需要的一切。如果您需要其他代码,请与我们联系。

1 个答案:

答案 0 :(得分:7)

移动findViewById()来电

EditText pressure = (EditText) findViewById(R.id.editTextPressure);
EditText temperature = (EditText) findViewById(R.id.editTextTemperature);
EditText volume = (EditText) findViewById(R.id.editTextVolume);
TextView answer = (TextView) findViewById(R.id.textViewSolve);
Button solve = (Button) findViewById(R.id.buttonSolve);

所以他们在setContentView(R.layout.activity_number);

之后

findViewById()如果在布局中找不到null,将返回View。如果没有布局,则无法找到View。首次实例化Activity时,肯定没有设置布局。