Erik Balen
Erik Balen

Reputation: 275

Why do I get this error - RunTimeException: Unable to instantiate activity?

My LogCat is saying:

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}

Here is my java file:

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));
        }
    });
}

}

Hopefully that is all you need. Let me know if you need additional code.

Upvotes: 2

Views: 59

Answers (1)

A--C
A--C

Reputation: 36449

Move the findViewById() calls

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);

So they are after setContentView(R.layout.activity_number);

findViewById() will return null if it can't find the View in the layout. If there is no layout, there is no View to find. There is definitely no layout set when the Activity is first instantiated.

Upvotes: 7

Related Questions