Search code examples
javaandroidscopeinstances

How can I access my Activity's instance variables from within an AlertDialog's onClickListener?


Here's a very simplified version of my Activity:

public class Search extends Activity {

    //I need to access this.
    public SearchResultsAdapter objAdapter;

    public boolean onOptionsItemSelected(MenuItem itmMenuitem) {


      if (itmMenuitem.getItemId() == R.id.group) {

          final CharSequence[] items = {"Red", "Green", "Blue"};

          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setTitle(itmMenuitem.getTitle());

          builder.setSingleChoiceItems(lstChoices),
              0, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {
                  //I need to access it from here.
                }

              });

          AlertDialog alert = builder.create();
          alert.show();

          return true;

        } 

    }

}

When the menu button is pressed, my applications pops up an AlertDialog. When creating the AlertDialog and in-line onClickListener is attached to the each of the items in the dialog. I need to access the objAdapater variable that is defined in my Search activity. I don't have access to the search instance within my onClickListener so I can't access it. I have a little bit of a soup in my code with the passing of the Activity instance everywhere. Maybe I'm doing something wrong.

How would I get access to the Activity (Search instance) from within my onClickListener so I can access it's methods and variables.

Thank you.


Solution

  • Using Search.this.objAdapter to access objAdapter from the listener should work.

    Search.this refers to the current instance of Search and allow you to access its fields and methods.