billo billo - 2 years ago 77
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download