How I usually access my Application:
MyApplication myApp = (MyApplication)this.getApplication();
but this can't be done from
public class MyArrayAdapter extends ArrayAdapter<SomeObject> {}
because getApplication() is an activity method. Is there a way to access the Application from an ArrayAdapter?
If you create a constructor for your Adapter that asks for the calling activity to pass a MyApplication parameter, you could then use that object. For example:
private MyApplication myApp;
public void MyArrayAdapter(MyApplication app){
myApp = app;
//do other setup stuff here
}
Then, to create the adapter in the activity you could do something like:
MyArrayAdapter myAdapter = new MyArrayAdapter(this.getApplication());
Generally speaking, your application should be singleton of your program. So, the easiest way to do this is to make a static reference of your application object.
class MyApp extends Application {
static MyApp myAppInstance;
public MyApp() {
myAppInstance = this;
}
public static MyApp getInstance() {
return myAppInstance;
}
}
Then in your adapter you can just call MyApp.getInstance()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With