0

I am currently trying to write a memory game where there are 4 boxes and among the 4 boxes there will be 4 which are selected randomly. Then the users have to memorize them and input the 4 boxes in correct order.

However I am currently facing a problem. It seems like handler only allows final variable. This is my code:

private OnClickListener click1 = new OnClickListener() {

 @Override
    public void onClick(View v) {
            final ImageButton[] all= {btn1, btn2, btn3, btn4};

            for (int a=0;a<4;a++) {

            handler1.postDelayed(new Runnable() { //start delay a

                @Override
                public void run() {
                //actions start

                btn5 = all[random.nextInt(all.length)];
                btn5.setBackgroundColor(Color.RED);

                handler1.postDelayed(new Runnable() { //start delay b
                @Override
                public void run() {

                btn5.setBackgroundResource(R.drawable.btn_default_holo_dark); 

                }}, 500); //end delay b 
                //action end

                }}, 1000*a ); //end delay a

                } 
            } 
        };

I try to put 4 variable inside to store the data of the btn5 but it doesn't work and it shows an error as a must be final.

               btn5 = all[random.nextInt(all.length)];

               if (a==0) {ans1 = btn5;} //error
               else if (a==1) {ans2 = btn5;} //error
               else if (a==2) {ans3 = btn5;} //error
               else if (a==3) {ans4 = btn5;} //error

               btn5.setBackgroundColor(Color.RED);

Is there any method to allow my if else statement? or is there any other method to allow me to store btn5 data in order?

joragupra
  • 692
  • 1
  • 12
  • 23
user3153613
  • 255
  • 1
  • 2
  • 10
  • how about `for (int a=0;a<4;a++) { final int aValue = a; ...` and use that aValue in those comparings – vilpe89 Jan 03 '14 at 12:46

2 Answers2

0

Declare your all array outside the listener, at class level and reuse it

MariusBudin
  • 1,277
  • 1
  • 10
  • 21
  • the `all` is not a problem but the `a` is the problem. It does not allow me to put `if else` to it – user3153613 Jan 03 '14 at 12:43
  • Oh, ok, then you overcomplicated it, it's easier than that, do a for each loop, in java it's like this http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work in your case would be something like `for (ImageButton btn : all)` – MariusBudin Jan 03 '14 at 12:50
0

One way is to declare final variable inside the for loop so the anonymous inner class can access to it. So add this line before handler1.postDelayed(new Runnable() { //start delay a:

final int aValue = a;

and then replace the a from the if/if else's with that aValue. Like this:

if (aValue==0) {ans1 = btn5;}

That how the anonymous inner class can get the value declared in the for loop.

vilpe89
  • 4,656
  • 1
  • 29
  • 36