"percentage can not be resolved to a variable"

4

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

Follow 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;
    
asked by anonymous 23.11.2014 / 06:32

1 answer

3

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

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

// Spinner
...
    
23.11.2014 / 06:47