0

I am having an integer variable and I want to change it when button is pressed but code doesn't work. Is says that I should set bpm to final but when I do I cant increase it!

Java code:

super.onCreate(savedInstanceState);
int bpm;
setContentView(R.layout.activity_metronome);
final Button plus = (Button) findViewById(R.id.tempop);
final Button minus = (Button) findViewById(R.id.tempom);
final Button confirm_tempo = (Button) findViewById(R.id.confirmtempo);
final TextView curbpm = (TextView) findViewById(R.id.curbpm);
bpm=60;
curbpm.setText("" + bpm);

plus.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        bpm++;
        curbpm.setText(""+bpm);
    }
});
Barney
  • 2,355
  • 3
  • 22
  • 37

1 Answers1

4

Make it class-scoped This means take it out of the method.

int bpm;
@Override
protected void onCreate (Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_metronome);
  final Button plus = (Button) findViewById(R.id.tempop);
  final Button minus = (Button) findViewById(R.id.tempom);
  final Button confirm_tempo = (Button) findViewById(R.id.confirmtempo);
  final TextView curbpm = (TextView) findViewById(R.id.curbpm);
  bpm=60;
  curbpm.setText("" + bpm);

  plus.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
      bpm++;
      curbpm.setText(""+bpm);
    }
  });
}

It's also cleaner to use String.valueOf (bpm) instead of ""+bpm.

A--C
  • 36,351
  • 10
  • 106
  • 92