wufoo
wufoo

Reputation: 14571

Static methods vs. class extending android.app.Application?

I have a class which extends Application in an Android tabHost app. In the App class, I've been placing methods and variables which I would otherwise need to re-create in every class. One method reads from a DB and stores results in an ArrayList (first name, last name for instance). Rather than re-reading this database and re-creating the code for every tab view which needs the info, I've stuck the method and ArrayList in a class extending Application (myAppClass). This way, by setting up mAC = (myAppClass) getApplicationContext() from any tab view in onCreate() I can reference all the get..() and set..() methods in myAppClass.

My original plan was to use a shared class with static methods and variables but I read a lot of "don't do that" threads so decided to go the Application route. Now, I've run into a situation where I'm trying to use myAppClass in a Project Library but getting errors about android.app.Application cannot be cast to... If I change myAppClass back to static methods/variables (and do not extend Application) things work, but this is supposed to be a big no-no. Is there another way to do this? Not sure if Android passes everything by reference but Would I be better off to re-implement the entire application by passing huge (thousands of objects/members) ArrayLists back-and-forth between methods/classes?

Upvotes: 4

Views: 2311

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006624

My original plan was to use a shared class with static methods and variables but I read a lot of "don't do that" threads so decided to go the Application route.

The "don't do that" is generally a recommendation against anything in global scope and therefore would cover static data members as well as a custom Application. Both are likely sources of memory leaks.

Now, I've run into a situation where I'm trying to use myAppClass in a Project Library but getting errors about android.app.Application cannot be cast to...

Your manifest in the hosting project probably does not state to use the library's Application implementation.

this is supposed to be a big no-no

Again, static data members are no worse than a custom Application, and in many cases are better.

Is there another way to do this?

Don't use either an Application or static data members.

Would I be better off to re-implement the entire application by passing huge (thousands of objects/members) ArrayLists back-and-forth between methods/classes?

You would be better off having a persistent data model, such as a database. Using static data members as a cache for a persistent data model is OK, so long as you are very careful about your memory management.

Upvotes: 6

Related Questions