1

I need to set the return value of this method to be the item selected in a Single Choice Dialog...

However, i cannot set the value of retVal because it apparently needs to be final (therefore cannot be changed)

Is there any way to do this without using global variables?

private String getSaleType()
{
    String retVal = "";
    final String[] TYPES = {"Cash Sale", "Sales Order"};
    AlertDialog.Builder choose = null;

    try
    {
        choose = new AlertDialog.Builder(this);
        choose.setIcon(R.drawable.firstdroidicon);
        choose.setTitle("Sale Type");
        choose.setMessage("Type Of Sale?");
        choose.setSingleChoiceItems(TYPES, currentItem, new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Log.i("Selected", TYPES[which]);
            }
        });
        choose.setPositiveButton("OK", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                retVal = TYPES[which];
            }
        });

    }
    catch(Exception e)
    {
        messageBox("getSaleType", e.getMessage());
    }

    return retVal;
}
Louis Evans
  • 671
  • 2
  • 8
  • 18
  • 1
    declare the variable as a class member – Raghunandan Aug 13 '13 at 10:53
  • @Raghunandan I would like to avoid doing this...i dont like having loads of variables declared at the top of the class. Can you explain why retVal has to be final? – Louis Evans Aug 13 '13 at 10:59
  • i don't know any other way other than what i have suggested. bcoz you have you have inner class and a method inside it. so it should be final – Raghunandan Aug 13 '13 at 11:00
  • Can't this be done with `String retVal1 = ""; final String retVal = "";` and then before the return do `retVal1 = retVal;` and return `retVal1`. Anyway what's the problem with `final` in this case, you're not using this variable more than once and after that you just return it? – g00dy Aug 13 '13 at 11:03
  • @LouisEvans http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-differen. here's an explanation on the topic – Raghunandan Aug 13 '13 at 11:04

1 Answers1

1

Not possible.

You can find that in JLS # chapter 8

Any local variable, formal parameter, or exception 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
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307