15

in Java android application how can i access variables of outer class from the inner anonymous class ? Example:

    ProgressDialog dialog = new ProgressDialog(this);
    .....
    send.setOnClickListener(new View.OnClickListener() 
    {
        public void onClick(View v) {

           //here i'd like to do something with **dialog** variable
           .......

        }
    });
user1246620
  • 151
  • 1
  • 1
  • 3

3 Answers3

29

If the dialog variable is a field of the outer class, you can use this prefixed with the outer class name (a qualified this):

send.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v) {
       ProgressDialog dlg = OuterClass.this.dialog;
       .......
    }
});

Alternatively, if the dialiog variable is a local variable it needs to be marked as final:

final ProgressDialog dialog = new ProgressDialog(this);
.....
send.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v) {
       // The dialog variable is in scope here ...
       dialog.someMethod();
    }
});
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
4

Make the outer local variable (dialog) final so you can refer to it from the inner class.

Arnout Engelen
  • 6,709
  • 1
  • 25
  • 36
1

If it's a local variable (like the signature suggests), it needs to be final for the inner class to be able to access it. If it's a member variable, the visibility modifier needs to be default (no modifier) or higher (protected or public). With private -modifier, it still works, but you might get a warning (depending on your compiler-settings):

Read access to enclosing field SomeClass.someField is emulated by a synthetic accessor method

esaj
  • 15,875
  • 5
  • 38
  • 52
  • 1
    The part about member variables is not true. Inner classes can access private members of the enclosing class -- the compiler generates hidden accessors for such members. – casablanca Mar 03 '12 at 09:56