student student - 6 months ago 39
Java Question

How to add a counter in Java?

The app stops. Where am I wrong? The button when clicked change the text to the number of times the item was clicked.

private Button button;
int countClicks = 0;

protected void onCreate(Bundle savedInstanceState) {

button = (Button) findViewById(;

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

Answer Source

That's a classic mistake

You are using View.setText() on an int, and it needs to be on a String. Try

 button.setText(countClicks + "");

By concatenating the integer with an empty String, it will auto-cast it to a String

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