How can I get a reference to an outer class from an inner class without using the name of the outer class?

Here is a sample code:

Class SomeClass extends Activity {
    public void someMethod() {
        Runnable r = new Runnable() {
            public void run() {
                Intent service = new Intent(SomeClass.this, SomeOtherClass.class);
                // ...
            }
        }
    }
}

How can I change the code so as not to use SomeClass(in new Intent(SomeClass.this, ...))? I want to place this sample in several classes, and I don't want to use a different class name each time.

+5
source share
1 answer

Shorter method (recommended):

Replacing SomeClass.thisyour intention with help getApplicationContext()should do the trick.

The method I use (a bit more elongated and probably not the best of the two):

In each class do a private Context mContext;
Then in onCreate()each class do mContext = this;
Finally, replace SomeClass.thisin your intention with mContext.

+3
source

All Articles