billo billo - 1 year ago 45
Android Question

App is crashing when I run it

I do not get any errors but when I run the app it crashes:

public class MainActivity extends AppCompatActivity {
ImageButton Nr1 = (ImageButton) findViewById(;
public void machwas(View v) {

protected void onCreate(Bundle savedInstanceState) {

Answer Source

This here is wrong:

public class MainActivity extends AppCompatActivity {
    ImageButton Nr1 = (ImageButton)findViewById(;

because findViewById() should be called INSIDE the onCreate method, the reason is that after that are layouts inflated and you are ready to get the views and initialize the widgets...

so what you are doing is initializing the ImageButton wrongly, probably will be null after that line and then this here

public  void machwas(View v){

is going to explode with a NullPointer Exception...

but this is only an inference because you dont post the LogCat...

For more info please take a look to the Activity lifeCycle and the Official Android Documentation

enter image description here