Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: cannot assign a value to final variable

I am facing the following issue with Android Studio

public class MainActivity extends AppCompatActivity {

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

    final int numeroHomem = 0;
    final int numeroMulher = 0;
    final int numeroPessoas = 0;

    final TextView campoTexto = (TextView) findViewById(R.id.pessoas);
    final Button botaoHomem = (Button) findViewById(R.id.homem);
    final Button botaoMulher = (Button) findViewById(R.id.mulher);
    final Button botaoReset = (Button) findViewById(R.id.reset);

     botaoHomem.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v){
            numeroHomem++;
            numeroPessoas++;
            String mensagem = Integer.toString(numeroPessoas);
            campoTexto.setText("Total: " + mensagem + " pessoas");
            botaoHomem.setText(Integer.toString(numeroHomem));
         }
     });
 } }

error: cannot assign a value to final variable numeroHomem
error: cannot assign a value to final variable numeroPessoas

like image 950
Goji Berry Avatar asked Apr 18 '26 07:04

Goji Berry


1 Answers

you cannot change final variable after initialization

what you can do is declare your variable in your class instead of onCreate()

public class MainActivity extends AppCompatActivity {

    int numeroHomem = 0;
    int numeroMulher = 0;
    int numeroPessoas = 0;

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


      final TextView campoTexto = (TextView) findViewById(R.id.pessoas);
      final Button botaoHomem = (Button) findViewById(R.id.homem);
      final Button botaoMulher = (Button) findViewById(R.id.mulher);
      final Button botaoReset = (Button) findViewById(R.id.reset);

      botaoHomem.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                numeroHomem++;
                numeroPessoas++;
                String mensagem = Integer.toString(numeroPessoas);
                campoTexto.setText("Total: " + mensagem + " pessoas");
                botaoHomem.setText(Integer.toString(numeroHomem));
            }
          });
    }
}
like image 105
Ali Faris Avatar answered Apr 19 '26 22:04

Ali Faris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!