Baffo rasta Baffo rasta - 2 months ago 20
Android Question

Why does this Android application immediately crash?

I leave you the code:

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
RelativeLayout layout = (RelativeLayout)findViewById(R.id.disposizione);
Button pulsante = new Button(this);
pulsante.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
pulsante.setText("Click me");
pulsante.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Thug life bitch!", Toast.LENGTH_LONG).show();
}
});

layout.addView(pulsante);
setContentView(R.layout.main);
}


I tried to remove all the lines from the RelativeLayout to the layout.addView one and so it works again!

What's wrong in this code? I must say that I don't get any build error or warnings.

Thanks in advance.

Answer

write setContentView() immediate after super.onCreate()

super.onCreate(savedInstanceState);

setContentView(R.layout.main);