I'm working on an application that consist of a couple of activities:
Below some more information:
Since now, I've been using bundles to exchange data between activities but it seems to complicate the code as the number of actions grow (some actions use a 3-4 activities to collect data from the user). Passing all the data to every created activity doesn't seems to be nice.
I'm thinking about storing the "user name" and selected "event" as a static fields of a class. I will simplify the code very much, but I'm not sure whether this data will persist if the user let say at some point press "home button" and run another application that needs a lot of memory.
Will the data stored in static fields be safe?
Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.
Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.
Static Methods/Variables are bad practice. In short: Yes. There are many disadvantages and static methods should almost never be used. Static methods allow procedural/functional code to be shoe-horned into an Object Oriented world.
Benefits of static variables: constants can be defined without taking additional memory (one for each class) constants can be accessed without an instantiation of the class.
It's better to have a custom Application object and store them there. The application object will live aslong as your app does.
http://developer.android.com/reference/android/app/Application.html
You can get access to the Application object by casting getApplicationContext() to whatever your custom Application type is:
public class CustomApplication extends Application {
private String userId;
public void onCreate() {
super.onCreate();
...
}
public String getUserId() {
return userId;
}
...
}
From Activity call: ((CustomApplication) getApplicationContext()).getUserId();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With