student student - 1 month ago 8
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