0

Why am I getting an java.lang.runtimeexception: Unable to instantiate activityComponentInfo {com.example.carprofile/com.example.carprofile.CarRegistraion}: java.lang.NullPointerExceprion

This is my code:

public class CarRegistration extends Activity{

//ParseXML parseClass;
Button saveCar;
EditText carMake = (EditText) findViewById(R.id.etCarMake);
EditText carModel = (EditText) findViewById(R.id.etCarModel);
String newCar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.car_registration);

    saveCar = (Button) findViewById(R.id.bSaveCar);
    saveCar.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            newCar = carMake.getText() +" "+ carModel.getText();
            //parseClass = new ParseXML(newCar);
            //parseClass.editXML();
        }
    });
}

if I clear the onCreate method, from saveCar = (Button)..., everything works fine.

Can someone tell me what am I doing wrong?

Student22b
  • 79
  • 3
  • 13
  • Wich line is throwing the exception? – Fustigador Oct 27 '13 at 16:51
  • 1
    a stacktrace would be more helpful – ajc Oct 27 '13 at 16:52
  • You are getting a `NullPointerException` because you have a null pointer exception. Post exception and point us to the line it indicates. It is likely due to your `EditText` views not being inflated. – skynet Oct 27 '13 at 16:52
  • If `saveCar = (Button)findViewById(R.id.bSaveCar);` is the problem line, you may need to post the XML. And speaking of which, there's a better way of handling `onClick` methods than what you're doing. – nhgrif Oct 27 '13 at 16:58
  • I found a problem: EditText carMake = (EditText) findViewById(R.id.etCarMake); EditText carModel = (EditText) findViewById(R.id.etCarModel); this two lines were the problem. I just move them in onCreate function, now there are no problems. Thank you all – Student22b Oct 27 '13 at 17:10

1 Answers1

0

Try this,

public class CarRegistration extends Activity{

     Button saveCar;
     String newCar;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.car_registration);

  EditText carMake = (EditText) findViewById(R.id.etCarMake); //these lines should be     after setContentView()
  EditText carModel = (EditText) findViewById(R.id.etCarModel);
  saveCar = (Button) findViewById(R.id.bSaveCar);
  saveCar.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        newCar = carMake.getText() +" "+ carModel.getText();
        //parseClass = new ParseXML(newCar);
        //parseClass.editXML();
    }
});

}

muntasir2000
  • 204
  • 1
  • 3
  • 11