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

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?

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.

Related

What are the downsides of having a static Context variable in an Android application?

In Android programming the single most used parameter that is passed almost everywhere is Context. And we know the purposes it serves. But we can't find out why we should pass it for those purposes, and why not accessing it from a global static place.
Based on Uncle Bob's Clean Code, one way of getting cleaner code is by reducing parameters, making them more meaningful to the task you're doing. Based on this, and based on DRYing parameters, we decided to give it a shot, and create a fully-featured application that has activities, fragments, foreground and background services, notifications, media, etc. and uses many device APIs like camera, GPS, etc. and is a real-world application, and only have one static context initialized at the application creation.
So in the application creation we created a public static Context context variable, and we initialized it using getApplicationContext() method in onCreate() override.
Then instead of passing context like this, getContext, etc. throughout code, we simply used App.context, and we didn't pass it as a constructor parameter to our adapters and other utility functions.
Now after venturing this bold movement, we don't see any problem with our app. Everything works just fine, battery consumption is not changed, at least it's not measureable to us so it's very low. Memory consumption is not changed and we can't measure it. Application performance and speed is not changed measurably.
So we have this really big question in our mind that, what are the downsides on our approach? Why Android guys don't just expose a global context that can be initialized and remove all context parameters from the entire ecosystem, only accessing that global variable anytime they need it?
Please read this blog carefully you will understand Context better.
Static variables defined at global scope of the class and so they also refereed as class member.
You can not control creation and destruction of static variable.
Usefully they have been created at program loading and destroyed
when program unload.
Since static variable are class member, all threads tries to access
them has to be manage.
If one thread change value of a static variable that can possibly
break functionality of other threads.
In my projects, I use the static application context for everything except graphics. The fact is that the application context does not contain information about the style and if you create a widget based on it, then it will have a default style.
On this moment, I have never faced the problems of this approach. Importantly, I do not write tests for my projects. But I'm sure that this will not be a problem.
I also will be very grateful if you point me to the problems of such use of the context. (except testing)
Your application doesn't break because you are using the Application Context: this may not be THE best practice, but it is generally fine.
What you are missing there is that Context is an abstract class with many different implementations (an Activity is a Context, a Service is a Context, the Application is a Context) with different properties and capabilities. The Activity has an entire graphic context associated whit it and a full view hierarchy that can occupy megabytes in memory.
One common mistake (that I did myself in my early days) was to store the Activity in a static field: this led to memory leaks by having two entire views hierarchy in memory as soon as the user puts the app in background, the Activity reaches onDestroy(...) callback and the user opens the app again.

Android preferred pattern to store globally needed objects

I have read through similar questions but have not found the best solution yet. So for example, I load user data from server on application startup. The info is later used in many application components. I do not feel comfortable storing it in singleton (for example, in Application) and make it globally acceptable. The other options I could think of is storing it in shared preferences as JSON or storing it in database. But these approaches might cause some performance hits. How do you solve this common problem?
It seems the best approach is to extend the Application class and add your global variables in, the other Stack Overflow question below could help:
Android Global Variable
Also, if you have a look to the javadoc of Application class it says clear for global application state use.
Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.
See the full Javadoc here
If you want to access data for all the activities, you can try making a base activity that extends activity and then using base activity as your base class for your other activities
public class MainActivity extends BaseActivity
Then for the BaseActivity
public class BaseActivity extends Activity
In the BaseActivity, store all your values as global variables, these variables can then be passed by each activity that extended base activity
I think you should use Shared Preferences to make the data available throughout you app. Alternativly, you could store your data on internal memory or cache. Depends on the amount of data, depends if you want it to be available between session.
Please read http://developer.android.com/guide/topics/data/data-storage.html for an overview of your options.

Global variable in main activity?

I'm new to Android (and Java) and was trying to find out where to store my global variables that I need in my various Activities, Fragments, etc. so I can easily access them, as well as saving and restoring them when the app is paused (a process that not yet fully understand, but that is not my question).
So the general consensus seems to be to use Singletons by extending Application (like described here).
Now that I played around some more I was wondering what is the reason against declaring variables in the main activity (e.g.final static int myVariable) and then accessing the variable trough MainActivity.myVariable? What is the downside?
Thank you in advance!
First, consider to design your app without needing global variables in the first place. Using global state variables might seem like an easy solution at first, but will complicate testing and maintenance later.
If you absolutely must, the application class is the correct place because it's lifecycle is your application's lifecycle. You can also use regular member variables instead of statics.
If you store variables in an activity class as static variables, the downsides include but are not limited to:
Loading another activity class needs to load all the code in the main activity as well.
Unnecessary dependency from activity to another, creating increased coupling.
statics are harder to mock/inject for example in a testing setup. A thin application object with member vars is easier to mock.
You can make a class that is subclass of Application, and scope of this class will be application wide, so you can access variable globally ( across the activities/fragment)
here you will get related info
there is no downside declaring your global variable as static unless the variable is bound to Context...
it is bad way to maintain static reference for Context (like Activity, Service), Views, Drawables and application Resources...
and some one said in SO (I didn't remember), Android will clear static memory in low memory situations...
For example if you are in "FirstActivity" that calls "SecondActivity", using startActivityForResult, to add a Product do a list, in "SecondActivity" you can CANCEL or ADD this product, if you ADDED it you whant to refresh the Product's list in "FirstActivity" so in "SecondActivity" you can use a "private static final int ADDED = 1" and a "private static final int CANCELED = 2" and pass one of this attributes in the setResult's method of "SecondActivity", before call the finish method, in FirstActivity's "onActivityResult" method you can verify if the "resultCode" is "SecondActivity.CANCELED" or "SecondActivity.ADD" and performe the list's refresh or not.
Just an example..
You can use Application's class (OS save variable in memory while app not destroy) or SharedPreferences (OS save variable to file permanent).

Move Sensor data to a different class/activity

I have a simple app, it logs a bunch of sensor/gps data. The first activity is a mess, and way too long, so i wanted to modularize it. I want to have 3 modules now:
Main Activity
Sensor Data (Gyroscope, accelerometer, etc)
GPS Data (Position, elevation, etc)
What is the best way for me to go about modularizing this? I was trying to move some of the Sensor Data out of the original class, and then I noticed that my class needed to extend some android.content.context (such as an Activity) in order to access the sensor data properly?
Thanks for a nudge in the right direction.
From my comments on the original question...
You don't need to extend Context - you can create helper classes and simply pass the Activity Context into the class constructor or into the various methods using this from the Activity.
As long as you design your helper classes correctly then it is fine and it is something that many people do and, indeed, there are various Android classes which require a Context parameter. Avoid memory leaks and use the right Context.
Sometimes using the application Context might be better as it is persistent for the life-time of all application components. It is, however, only a partial context in that certain things won't work with it (some UI-related tasks, for example). Otherwise using the Activity Context is fine as long as nothing holds a permanent reference to it (which can cause memory leaks if the Activity is destroyed.

Using the Android Application class to persist data

I'm working on a fairly complex Android application that requires a somewhat large amount of data about the application (I'd say a total of about 500KB -- is this large for a mobile device?). From what I can tell, any orientation change in the application (in the activity, to be more precise) causes a complete destruction and recreation of the activity. Based on my findings, the Application class does not have the same life-cycle (i.e. it is, for all intents and purposes, always instantiated). Does it make sense to store the state information inside of the application class and then reference it from the Activity, or is that generally not the "acceptable" method due to memory constraints on mobile devices? I really appreciate any advice on this topic. Thanks!
I don't think 500kb will be that big of a deal.
What you described is exactly how I tackled my problem of losing data in an activity. I created a global singleton in the Application class and was able to access it from the activities I used.
You can pass data around in a Global Singleton if it is going to be used a lot.
public class YourApplication extends Application
{
public SomeDataClass data = new SomeDataClass();
}
Then call it in any activity by:
YourApplication appState = ((YourApplication)this.getApplication());
appState.data.UseAGetterOrSetterHere(); // Do whatever you need to with the data here.
I discuss it here in my blog post, under the section "Global Singleton."
Those who count on Application instance are wrong. At first, it may seem as though the Application exists for as long as the whole app process exists but this is an incorrect assumption.
The OS may kill processes as necessary. All processes are divided into 5 levels of "killability" specified in the doc.
So, for instance, if your app goes in the background due to the user answering to an incoming call, then depending on the state of the RAM, the OS may (or may not) kill your process (destroying the Application instance in the process).
I think a better approach would be to persist your data to internal storage file and then read it when your activity resumes.
UPDATE:
I got many negative feedbacks, so it is time to add a clarification. :) Well, initially I realy used a wrong assumption that the state is really important for the app. However if your app is OK that sometimes the state is lost (it could be some images that will be just reread/redownloaded), then it is fully OK to keep it as a member of Application.
If you want to access the "Global Singleton" outside of an activity and you don't want to pass the Context through all the involved objects to obtain the singleton, you can just define a static attribute in your application class, which holds the reference to itself. Just initialize the attribute in the onCreate() method.
For example:
public class ApplicationController extends Application {
private static ApplicationController _appCtrl;
public static ApplicationController getAppCtrl()
{
return _appCtrl;
}
}
Because subclasses of Application also can obtain the Resources, you could access them simply when you define a static method, which returns them, like:
public static Resources getAppResources()
{
return _appCtrl.getResources();
}
But be very careful when passing around Context references to avoid memory leaks.
Dave, what kind of data is it? If it's general data that pertains to the application as a whole (example: user data), then extend the Application class and store it there. If the data pertains to the Activity, you should use the onSaveInstanceState and onRestoreInstanceState handlers to persist the data on screen rotation.
You can actually override the orientation functionality to make sure that your activity isn't destroyed and recreated. Look here.
You can create Application class and save your all data on that calss for use that anywhere in your application.
I know this is the very old question but using the ViewModel from the jetpack components is the best way to preserve the data between Activity rotation.
The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

Categories

Resources