rits
rits

Reputation: 1544

App crashes on button tap

I tried two different ways of executing some code on button tap, one works and the other crashes the app on my phone which has Android 4.1.

If I add on click listener inside onCreate method then it works, but if I do it in different method then app crashes (I did add method name to onClick event for the button).

This works:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button button = (Button) findViewById(R.id.button1);
    if (button != null) {
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
                if (progressBar != null) {
                    progressBar.setVisibility(View.VISIBLE);
                }
            }
        });
    }
}

This crashes the app on button tap:

protected void playOnClick (View v) {
        Button button = (Button) v;
        if (button != null) {
            ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
            if (progressBar != null) {
                progressBar.setVisibility(View.VISIBLE);
            }
        }
    }

Any idea why? Started learning Android development today.

EDIT:

Changing method playOnClick from protected to public fixed crash.

Upvotes: 0

Views: 69

Answers (2)

rits
rits

Reputation: 1544

Changing method playOnClick from protected to public fixed the crash.

public void playOnClick (View v) {
    Button button = (Button) v;
    if (button != null) {
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
        if (progressBar != null) {
            progressBar.setVisibility(View.VISIBLE);
        }
    }
}

Upvotes: 1

sokarcreative
sokarcreative

Reputation: 526

Considering that your button and progressbar are present in your "activity_main" layout, the safety way to bind views in your onCreate() should be something like that :

private Button button;
private ProgressBar progressBar;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button1);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressBar.setVisibility(View.VISIBLE);
        }
    });
}

App will not crash when using your method :

protected void playOnClick (View v) {
    progressBar.setVisibility(View.VISIBLE);
}

Upvotes: 0

Related Questions