"cannot be resolved to a variable percentage"

Asked

Viewed 367 times

4

I need to set the variable value porcentagem as defined in Spinner. The problem is that I need to use the value of porcentagem out of method setOnItemSelectedListener(), on the line int r = edtVaoNum * porcentagem / 100;, but that way the Eclipse points error.

Follows the code:

    EditText edtVao = (EditText) findViewById(R.id.vao);
    final int edtVaoNum = Integer.parseInt(edtVao.getText().toString());

    // Spinner
    Spinner spnCargas = (Spinner) findViewById(R.id.spn_cargas);
    ArrayAdapter<CharSequence> spnAdapter = ArrayAdapter.createFromResource(this, R.array.str_cargas, R.layout.spinner_style);
    spnAdapter.setDropDownViewResource(R.layout.spinner_dropdown_style);
    spnCargas.setAdapter(spnAdapter);
    // Spinner

    spnCargas.setOnItemSelectedListener(
            new AdapterView.OnItemSelectedListener() {

                public void onItemSelected(AdapterView<?> spnAdpView, View v, int carga, long id) {

                    int porcentagem;

                    if(spnAdpView.getItemAtPosition(carga).toString() == "Cargas pequenas"){ porcentagem = 4; }
                    else if(spnAdpView.getItemAtPosition(carga).toString() == "Cargas médias"){ porcentagem = 5; }
                    else { porcentagem = 6;}

                }// fecha onItemSelected

                public void onNothingSelected(AdapterView<?> arg0){}
            }//fecha OnItemSelectedListener
    ); // fecha setOnItemSelectedListener

    int r = edtVaoNum * porcentagem / 100;

1 answer

3


You are declaring the variable within the scope of the method, i.e., it is only valid within where you declared it, in case you declared it within the setOnItemSelectedListener() method then it will only be visible within the {} bounders of the method, i.e., its scope. So the solution is to declare the variable out of the method, like this:

EditText edtVao = (EditText) findViewById(R.id.vao);
final int edtVaoNum = Integer.parseInt(edtVao.getText().toString());
int porcentagem; //DECLARE AQUI

// Spinner
...
  • I did, but declaring the variable before the onCreate method. Thank you!

  • But you can understand the scope thing, right? In case if you declared inside onCreate, it would be visible anywhere inside onCreate, in all methods inside it etc. If you declared in a method still superior to onCreate (I don’t remember how is the structure of android) that must be a Main method, the variable is available on onCreate, onPause, onResume etc. Hugs. In need we are there =D

  • Got it, hugs bro! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.