5

Here is the 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 to not use SomeClass ( in new Intent(SomeClass.this, ...))? I want to place this sample in multiple classes and I do not want each time use different class name.

Prizoff
  • 4,486
  • 4
  • 41
  • 69

1 Answers1

3

Shorter method (suggested):

Replacing SomeClass.this in your Intent with getApplicationContext() should do the trick.

Method I use (a little more drawn out and probably not the best of the two):

In each class, make a private Context mContext;
Then, in the onCreate() of each class, make mContext = this;
Finally, replace SomeClass.this in your Intent with mContext.

Mxyk
  • 10,678
  • 16
  • 57
  • 76
  • 2
    this answer is good, and provide good solution, but I want to mention that holding reference to context with mContext should done carefully. it can easy lead to memory leek. – Tal Kanel Jul 18 '12 at 15:47
  • Solution is acceptable... And it seems that I will use it, thanks... But is there a pure java way to access outer class without any private fields and calling any methods of superclass (`Activity` in this case)? – Prizoff Jul 18 '12 at 15:53
  • If you have multiple classes in which you are creating a field to store a reference to the context, getting the context statically might be a a prefered way: http://stackoverflow.com/questions/2002288/static-way-to-get-context-on-android – Rik van Velzen Oct 26 '15 at 13:22