Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get android context from a reference of interface?

I have an activity which instantiate a class with an interface. How I can get the android context within MyClass with only the reference to the interface?

public class TestActivity extends Activity implements MyInterface {

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        final MyClass myClass = new MyClass(this);

    }

    @Override
    public void onChange() {

    }
}


public interface MyInterface {
    void onChange();
}

public class MyClass {
    public MyClass(MyInterface myInterface) {
       // how to get context from myInterface ???
    }
}
like image 329
Zip Avatar asked Oct 25 '25 12:10

Zip


1 Answers

public class MyClass {
    public MyClass(MyInterface myInterface) {
    // Get Context
    Context context = null;
    if (myInterface instanceOf Context)
        context = (Context)myInterface;
    }
}

If your Activity (which extends Context) is implementing MyInterface and you pass that to MyClass, you just need to cast it to the appropriate type.

like image 81
David Wasser Avatar answered Oct 28 '25 03:10

David Wasser