Static variables in Android - android

I defined static variables in Activities in order to pass complex data between Activities.
Many people suggest not to use any static variables in Android. Some people suggest to store global data in a custom android.app.Application. I don't think there is any difference between static variable and custom Application.
I'd like to know your thoughts on static variables. Any suggestions?
Thanks.

Dear god don't do that. If you need to pass objects between activities, use a service.

Static variables are per definition global variables as they are scoped to a class instead of to an instance.
Depending on your design , it might perhaps it's better/cleaner/easier to have these global variables centralized instead of scattered over a plethora of classes.
Furthermore, in traditional software engineering, global variables are considered a bad thing, and that is correct, but when programming in a platform as Android where resources are scarce and optimal use of the resources to boost performance are of most importance so you should be developing with a totally different mindset.
Global variables don't have to be too bad in such a case.
Please note that the Android platform also provides a Service interface which could fit your need for sharing variables between Activities.

Related

Android encrypt util class, make singleton or not

I have an android app which encrypts and uploads various files to AWS. The boiler plate code for AWS is a singleton, and I use that throughout my app. I have an encryption class as well, and I am currently instantiating encryption objects in various places, encrypting the file, and passing it to the singleton instance of the AWS upload class.
I am wondering if this is the best approach? Should i make the instance of the encryption object static? And have just one instantiated, and then call the encrypt method from different classes? In some places it is recommended, in others people say using static can be dangerous? Or is there a better way than either of these options?
Should note the app works fine as is, but I am a self taught Android dev, and I am trying to get better, but none of the tutorials go into heaps of detail about things like this.
Static is not dangerous, it's to share operations that don't depend on instances of objects. Like the Math class.
Singleton pattern is for controlling instances of objetcs of some class. If you want an instance, and only one instance, you use singletons. Generally, people use it to get that instance at a global scope. I think the Application class would fit this.
I prefer to use dependency injection if I am working with a lot of service classes. Encryption is a service to me, but you have to do the mechanism for dependency injection, or use a framework, but this is overkill to your problem.
I would go for the static methods this time.
Creating a Singleton class or making your object static, both are good options if you have to use the method of a class on various places. It's better to have a static object then creating the same object again and again.
So according to me the "Singleton" class is the best option to make your code efficient, but if you want to go with a static method/class then there is no harm in it. Static can be dangerous in some situations, like when you have to assign different values and get different values in different situations. Then there is a chance you can get wrong value in wrong situation. But in your case it's fine.

Is it safe to use static class variables in an android application

I am aware of the technique of extending the Application class to provide global storage. However in my case I am writing a class for a library function, so do not wish to force users of the class down this path. I have a requirement for some static class variables. I have seen passing references in StackOverflow that these might not be safe. However I've tried two different applications using the same class, and even when running both applications side by side on a Galaxy S3 in multi-window mode, the static class variables remain separate.
So, can someone with an in depth knowledge of Android internals confirm if this is safe or not.
If it is not safe, I can wrap the variables in a nested class and add them to a Serializable static HashMap, using the application package name as the key. This will force them to be safe. However if this is not necessary, then I'd rather not do it.
I have seen passing references in StackOverflow that these might not be safe.
They are not "safe" insofar as your process will be terminated from time to time, wiping out your static data members (and your custom Application, for that matter). Hence, static data members are good for a cache and not much else.
Within that scope, they are "safe".
You just need to make sure that this data is either stored somewhere persistent (e.g., file) or otherwise can be regenerated once the process is terminated and later is started up again. This is no different than with Application.
However I've tried two different applications using the same class, and even when running both applications side by side on a Galaxy S3 in multi-window mode, the static class variables remain separate.
Correct. Those are separate processes, with separate copies of your class and objects.
If your goal is to store persistant data across the twists and turns of the application lifecycle, then I would recommend not using static variables to do so. The obvious problem with this approach is that they could easily be garbage collected by the system when the operating system decides to reclaim memory (i.e. when the screen sleeps or a different application starts a memory-intensive task). I'm not sure what kind of data you are looking to "store", but I would recommend saving the state in SharedPreferences or an SQLiteDatabase instead.
I'm a little confused about what you're trying to do. You're trying to create a utility library in Java to be used by other applications? You're trying to create a whole Activity intended for use by other applications?
At any rate, as other posters have mentioned, applications can be killed at almost any time when resources become tight. There's simply no way to guarantee that static global values will remain resident in memory. You must provide a way to back it up on onPause() or onSaveInstanceState().
If you're writing a utility library, I presume that it returns some master object which holds all of its state. Add saveState(Bundle), restoreState(Bundle) methods to that object, and optionally saveToSharedPreferences() and restoreFromSharedPreferences() methods as well.
If it's an Activity you're writing, you're probably already familiar with the ways of saving state.
Me, I'm fond of combining the "singleton pattern" with shared preferences: https://stackoverflow.com/a/13673178/338479
You seem to have a deep misconception of how classes work.
Even if two classes are in the same package in two separate apps (by default) those apps run on separate VMs (i.e., processes). They literally have nothing to do with each other (as it should be, since otherwise you might get cross-app name collisions which is unacceptable).
What you're looking for is not a way to use static variables but a way to do inter-process communication (IPC). Android's Services are ideal for this, though there is a bit of a steep learning curve there.

Android global/common functions

Just started today to learn Android development, and I just can't find any info on how may I define a Helper class, or a collection of functions that will load globally and I'll be able to use them in any Activity that I create.
What I'm planning, is to create (at least for now) 2 functions that will be used almost in every activity, and would be a mess having to define the same functions in every activity.
Which would be the proper way to approach the above?
I want to throw out a quick note that you should not be putting functions in a global application class for this purpose. Generally what happens is that if you have shared functionality, you abstract that and put the code in:
Static methods
Another package
A library implementing the functionality against which you link your app
A content provider
You should explicitly not implement this functionality in the Application class. There are uses for extending the application, but doing so results in code smell and is a common antipattern for beginners. If you want a bunch of functionality which is shared in your app, a library is the perfect solution (even if it's just code you separate into another package). This encourages reuse and allows the code to be more cleanly segmented and tested.
It's common in Java to have either a class or pacakge of the form *.util for this.
(I'm guessing you come from something like a Rails world where this is the norm, since Ruby is much more metaprogramming oriented than Java, you generally use different tricks.)
This would be a static method in Java.
Java Static Methods
In a class Helper,
public static void DoSomething(){
}
Would be accessible from any class.
Example:
Helper.MyFunction();

How do I make application context available to all classes in application in the app?

How do I make application context available to all classes in application in the app?
My supporting classes need to be able to access it in order to access resourses.
Best answer: pass in a Context to your supporting classes' methods, as the application context may or may not work for your particular cases. You will notice, for example, that many supporting classes in Android take this approach, and it is generally a good idea to follow the patterns set forth by the platform developers.
Possibly tolerable answer: use a static data member to hold a reference to the Application object. Be very very careful that you do not introduce memory leaks in the process.

Android private fields naming guidelines are ok?

Here http://source.android.com/source/code-style.html#follow-field-naming-conventions it is stated that :
Field Names
Non-public, non-static field names start with m.
Static field names start with s.
Other fields start with a lower case letter.
Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.
It also states that :
The rules below are not guidelines or recommendations, but strict rules. You may not disregard the rules we list below except as approved on a need-to-use basis.
I don't like the "m" convention before private or package fields in a class. I really find this uninspired... I mean, if we try to apply good designs, the low coupling of the classes implies having few public fields. actually, in my programs I usually have no public fields, even when I need some I use getters and setters...
So, why should I be forced to have almost all my fields in the program with an "m" in front of them? wouldn't be easier to have the few public fields, if there are any, with some "g" in front or something? or just use setters and getters as beans suggest?
this really makes my code harder to read....
Also, following these guidelines, local temp variables used in the methods have no restriction so they could easily be mistaken for public global fields (also without restriction)... this also I find to be wrong, as it is a probable source of mistakes...
I understand to have a way of differentiating from fields, but private/protected member fields are the most used in an application, they shouldn't be less "readable".
What do you think? Should I follow the guidelines?
Those coding guidelines are for the Android Open Source Project which is the core Android Platform. You have to follow these guidelines if you want any of your code to be accepted into the core platform. You can do what ever you want in your own applications.
With regards to the guidelines themselves I think they are very reasonable and similar to many standards used in commercial applications. Generally you want to use getters and setters for public field access and you don't want to have global public variables. Only global public constants are ok.
So the short answer is follow them for the Open Source project, decide to follow them in you app.
In regards to getters\setters, it is actually recommended to not use them in Android.
I found this on the "Designing for Performance" page (section: Avoid Internal Getters/Setters): http://developer.android.com/guide/practices/design/performance.html
Bottom line, they infer that instance field lookups are more efficient than Virtual method calls (due to optimizations in the JIT).
I think I will continue to use getters\setters in my code, but this might be an easy way to improve performance (especially for apps that do a lot of data manipulation).

Categories

Resources