Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access variables of outer class in Java

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
           .......

        }
    });
like image 848
user1246620 Avatar asked Mar 03 '12 09:03

user1246620


People also ask

How do you access the outer class variables from an inner class?

Since inner classes are members of the outer class, you can apply any access modifiers like private , protected to your inner class which is not possible in normal classes. Since the nested class is a member of its enclosing outer class, you can use the dot ( . ) notation to access the nested class and its members.

Can inner class access outer class variables in Java?

Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.

How do you reference an outer class in Java?

In general you use OuterClassName. this to refer to the enclosing instance of the outer class.

What is access variable in Java?

The Java language supports five distinct access levels for variables: private, private protected, protected, public, and, if left unspecified, "friendly".


1 Answers

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();
    }
});
like image 131
Rich O'Kelly Avatar answered Nov 09 '22 22:11

Rich O'Kelly