-1

In some part of my app's code I have a method that shows an AlertDialog to get a value(number) from the user. But when I try to save it in a variable (int) and return it I get this compile error:

enter image description here

The error says: "Cannot refer to a non-final variable bet inside an inner class defined in a different method"

So I try making bet a final variable, getting a new error: "The final local variable bet cannot be assigned, since it is defined in an enclosing type"

My idea is to call that method, show the alert dialog, get the input value and return it.

Akram
  • 7,548
  • 8
  • 45
  • 72
azorrozua
  • 129
  • 1
  • 4
  • 12

3 Answers3

1

Declare bet as a Global variable.

public class SomeActivity extends Activity {
    int bet=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    private int betDialog() 
    {
        //some code...
    }
}
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
  • I tried this way but as the alert dialog doesn't block the rest of the processing, when I call betDialog() and in the next line I get the value of 'bet' I get '0' – azorrozua May 30 '12 at 10:11
0

You can simply assign the variable globally and use it.

For more explanation, see here,

Cannot refer to a non-final variable inside an inner class defined in a different method

And as mentioned here by jon-skeet

Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.

Community
  • 1
  • 1
Andro Selva
  • 53,910
  • 52
  • 193
  • 240
0

The "solution" to my problem I found is the next:

I moved the code that needed the users input inside the 'onClick();'

azorrozua
  • 129
  • 1
  • 4
  • 12