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;

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

button = (Button) findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
countClicks++;
button.setText(countClicks);
}
});

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