capcom
capcom

Reputation: 3337

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

I know this question has been asked several times before, but I upon reading many answers, I haven't found something which suits me. First, please look at the following code, which is supposed to open an AlertDialog once an image is clicked (this works perfectly). The AlertDialog hosts an EditText field - this is where the problem arises:

    ImageView scissorsImage = (ImageView) findViewById(R.id.scissorsImage);
    scissorsImage.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) 
        {
            AlertDialog.Builder alert = new AlertDialog.Builder(context);

            alert.setTitle("Apply a Coupon");
            alert.setMessage("Enter the coupon amount (i.e. 25 for $25)");

            // Set an EditText view to get user input 
            final EditText couponAmount = new EditText(context);
            alert.setView(couponAmount);

            couponAmount.setText(couponAmountString);

            alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String couponAmountString = couponAmount.getText().toString();
                    System.out.println(couponAmountString);
                }
            });

            alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // Canceled.
                }
            });

            alert.show();
        }

    });

Now, this bit of code is inside my onCreate method, and the variable couponAmountString is outside the onCreate method. So the code executes just fine, the only problem is that the line couponAmount.setText(couponAmountString); does not work as I want it to.

What I am trying to do with it is that when the user puts a value in the dialog box, and closes it by pressing OK, the value gets stored in couponAmountString - so far so good. When the user touches the image again to re-open the dialog box, I am trying to have the EditText field pre-set with the last value they entered, hence couponAmount.setText(couponAmountString);. But this isn't working, because I have to declare the EditText field as final. Which is why I get the error Cannot refer to a non-final variable inside an inner class defined in a different method when I click on the image the second time.

So is there any way I can accomplish what I want?

Thanks!

Upvotes: 0

Views: 934

Answers (1)

capcom
capcom

Reputation: 3337

Silly, silly me. It turns out that I was re-initializing couponAmountString inside the method as you can see. I just had to take out String and it's working now!

Upvotes: 1

Related Questions