Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access my Application from a custom ArrayAdapter?

Tags:

android

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?

like image 752
TimSim Avatar asked Oct 16 '25 23:10

TimSim


2 Answers

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());
like image 58
T3KBAU5 Avatar answered Oct 19 '25 19:10

T3KBAU5


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()

like image 38
Robin Avatar answered Oct 19 '25 19:10

Robin