2

I have a custom dialog with gridview in it. The dialog pops up when I click a textview(runs). There is a gridview in the dialog. My objective is to change value of runs textview on selecting the value from gridview and dismiss the dialog

    protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    switch (id) {
    case CATEGORY_ID:

        AlertDialog.Builder builder;
        AlertDialog alertDialog;
        // Context mContext = this;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.gridview_cell,
                (ViewGroup) findViewById(R.id.layout_root));

        GridView gridview = (GridView) layout.findViewById(R.id.gridView1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.layout.text_gridview, R.id.run_cell, numbers);

        gridview.setAdapter(adapter);

        builder = new AlertDialog.Builder(context);
        builder.setView(layout);
        dialog = builder.create();
        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {

                runs.setText(String.valueOf(position));
       **dialog.cancel() or dialog.dismiss are giving me this error: 'Cannot refer to a non-final variable result inside an inner class defined in a different method'**
            }
        });
        break;

    }
    return dialog;
}
vikas sharma
  • 161
  • 4
  • 13

1 Answers1

2

Instead of

Dialog dialog = null;

Do

final Dialog dialog;

For a better explanation of this, check this previously asked question.

Edit

I didn't see the rest of the problem. Seeing as you have a switch statement, you can just use default to set the value as follows:

protected Dialog onCreateDialog(int id) {
    final Dialog dialog;
    switch (id) {
        case CATEGORY_ID: 
           //your code
           break;
        default:
           dialog = null;
           break;
    }
    return dialog;
}
Community
  • 1
  • 1
Andrew Schuster
  • 3,229
  • 2
  • 21
  • 32
  • after your suggested change I get this error **"The local variable dialog may not have been initialized"** on line **return dialog;** – vikas sharma Nov 21 '13 at 21:18
  • @Andrew Schuster don't you get a Compilation Error in `dialog = null`? I mean an Error like `The final local variable dialog cannot be assigned, since it is defined in an enclosing Type` – Gödel77 Sep 17 '14 at 13:14
  • @Gödel77, I do not get such an error. Under what context do you receive that? Also, what's your IDE for Android? – Andrew Schuster Sep 18 '14 at 02:48
  • @AndrewSchuster in a normal custom Method in which I create a Dialog as final like you and then in onClick of positive/negative Button I wanted to ensure that the dialog closes , you know `dialog.dismiss()` + `dialog=null`. Regards – Gödel77 Sep 18 '14 at 06:00