Mike Baxter
Mike Baxter

Reputation: 7268

Referencing a dialog in a listener before dialog has been instantiated by dialog builder

I'm trying to build a nice little quick dialog box that lets the user choose a sync interval with the main server.

public void editSyncInterval(View view)
{

final AlertDialog intervalDialog;
final CharSequence[] items = { "1 minute", "2 minutes", "5 minutes", "10 minutes", "30 minutes" };

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Sync Interval");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener()
{
    public void onClick(DialogInterface dialog, int item)
    {
        switch(item)
        {
            case 0:
                //save
                intervalDialog.dismiss();
                break;
            case 1:
                //save
                intervalDialog.dismiss();
                break;
            case 2:
                //save
                intervalDialog.dismiss();
                break;
            case 3:
                //save
                intervalDialog.dismiss();
                break;
        } 
    }
});
intervalDialog = builder.create();
intervalDialog.show();
}

However, on the 4 lines that are intervalDialog.dismiss();, I get the following (rather expected) error: The local variable intervalDialog may not have been initialized.

I'm assuming that you need to call builder.create after you have already set up the listeners etc, but in which case - how do you reference the dialog itself - since you have not instantiated it yet?

Upvotes: 0

Views: 50

Answers (1)

Pankaj Kumar
Pankaj Kumar

Reputation: 83008

You get DialogInterface dialog as parameter into listener. You can call dismiss() on it.

You should use

 dialog.dismiss();

instead of

intervalDialog.dismiss();

Upvotes: 2

Related Questions