Static methods versus android.app.Application class extension?

I have a class that extends an application in an Android tabHost application. In the App class, I placed methods and variables that otherwise I would have to recreate in each class. One method reads from the database and stores the results in an ArrayList (first name, last name, for example). Instead of re-reading this database and re-creating the code for each type of tab, for which information is required, I fixed the method and ArrayList in the class extending Application (myAppClass). Thus, by setting mAC = (myAppClass) getApplicationContext() from any kind of tab in onCreate (), I can refer to all the get .. () and set .. () methods in myAppClass.

My initial plan was to use a common class with static methods and variables, but I read a lot of “don't do this” threads, so I decided to go along the application route. Now I am faced with a situation where I try to use myAppClass in the project library, but get errors in android.app.Application cannot be cast to... If I change myAppClass to static methods / variables (and do not extend Application), everything will work but it should be a big no no. Is there any other way to do this? Not sure if Android will pass everything by reference, but can I better implement the whole application by passing huge (thousands of objects / members) ArrayLists back and forth between methods / classes?

+4
source share
1 answer

My initial plan was to use a common class with static methods and variables, but I read a lot of “don't do this” threads, so I decided to go along the application route.

Do Not Do This is generally a recommendation against anything globally and therefore will cover static data members as well as the custom Application . Both are likely sources of memory leaks.

Now I am faced with a situation where I try to use myAppClass in the project library, but I get errors in android.app.Application cannot be different for ...

Your manifest in the hosting project probably does not indicate the use of the implementation of the Application library.

it's supposed to be a big no-no

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

Is there any other way to do this?

Do not use either Application or static data items.

Would it be better to reinstall the whole application, 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 elements as a cache for a persistent data model is fine if you are very careful about memory management.

+6
source

Source: https://habr.com/ru/post/1388325/


All Articles