Initialization of static variables in a class of utility functions - android

For my Android application, I have written a class which is composed of utility functions which are needed at various activites in the application.In this class, I need a context variable(for working with files) and an instance of preference manager and preference editor.Also, a long integer represnting the current date as a timestamp is needed:
private static long today;
private static Context myContext;
private static SharedPreferences sharedPrefs;
private static Editor editor;
Which is correct way to initialize these variables. I have tried doing it via a private constructor as shown below, but I am getting errrors.
private NetworkController()
{
//Getting the Unix timestamp for today
GregorianCalendar aDate = new GregorianCalendar();
GregorianCalendar tDate = new
GregorianCalendar(aDate.get(Calendar.YEAR),aDate.get(Calendar.MONTH),
aDate.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
today = (tDate.getTimeInMillis())/1000;
//The preferences manager for reading in the preferences
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(myContext);
//The preferences editor for modifying the preferences values
editor = sharedPrefs.edit();
}
One approach would be to create an instance of this class in every activity where its used but I don,t want to do that.Any other approach is possible?

If you have a set of things that you use everywhere and only want one instance of, you can use what's called a singleton. For example, here is a very simple one that holds an integer called level:
public class Utility {
private static Utility theInstance;
public int level;
private Utility() {
level = 1;
}
public static getUtility() {
if (theInstance == null) {
theInstance = new Utility();
}
return theInstance;
}
}
Then you can use this like:
Utility u = Utility.getUtility();
u.level++;
However, many people discourage the use of singletons, since they can lead to confusing program behaviour. A good article on this topic is Singletons are Pathological Liars. Singletons can be useful in some situations, but you should be aware of the traps involved in using them.

#Greg is right, just don't use any static stuff for what you want to do. There is no reason you don't want to have normal objects here. Pass the context as parameter and instanciate you objects when you need them to serve you :
private long today;
private Context myContext;
private SharedPreferences sharedPrefs;
private Editor editor;
public NetworkController( Context context )
{
this.context = context;
//Getting the Unix timestamp for today
GregorianCalendar aDate = new GregorianCalendar();
GregorianCalendar tDate = new
GregorianCalendar(aDate.get(Calendar.YEAR),aDate.get(Calendar.MONTH),
aDate.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
today = (tDate.getTimeInMillis())/1000;
//The preferences manager for reading in the preferences
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.context);
//The preferences editor for modifying the preferences values
editor = sharedPrefs.edit();
}
Singletons are a bad way of programming things, it makes things very hard to test. Even you don't yet use tests, don't use singletons, there lead to very poor quality code and real ball of muds when things get more complicated.

Here you can do this:
public class NetworkController {
SharedPreferences settings;
SharedPreferences.Editor editor;
public NetworkController(Context context){
settings = PreferenceManager.getDefaultSharedPreferences(context);
editor = settings.edit();
}
public void saveName(String name){
editor.putString("name", name).commit();
}
public String getName(){
return settings.getString("name");
}
public static long getTimeStamp(){
return System.currentTimeMillis();
}
}
You can use the class like below:
NetworkController prefs = new NetworkController(context); // Context being an Activity or Application
prefs.saveName("blundell");
System.out.println(prefs.getName()); // Prints 'blundell';
System.out.println(NetworkController.getTimeStamp()); // Prints 1294931209000
If you don't want to create an instance in every class you could create on instance in your Application and always reference that:
public class MyApplication extends Application {
private NetworkController myPrefs;
public NetworkController getPrefs(){
if(myPrefs == null){ // This is called lazy initialization
myPrefs = new NetworkController(this); // This uses the Application as the context, so you don't have issues when Activitys are closed or destroyed
}
return myPrefs;
}
}
You need to add the MyApplication to your manifest:
<application
android:name="com.your.package.MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
To use this single instance you would do this:
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
super(savedInstanceState);
NetworkController prefs = ((NetworkController) getApplicationContext()).getPrefs();
// use this object just like shown above
prefs.saveName("blundell"); // etc
}
}

There's already a bunch of good suggestions posted here, but I suppose another approach for these kind of 'utility'/'helper' functions is to simply pass in the parameters you need the logic to work on. In your case, in stead of trying to make the logic work on a local Context reference, you could simply pass it in:
public static void NetworkController(Context context) {
//Getting the Unix timestamp for today
GregorianCalendar aDate = new GregorianCalendar();
GregorianCalendar tDate = new
GregorianCalendar(aDate.get(Calendar.YEAR),aDate.get(Calendar.MONTH),
aDate.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
long today = (tDate.getTimeInMillis())/1000;
//The preferences editor for modifying the preferences values
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
...
}
The other variables you can calculate/deduce on the fly. It'll probably mean a bit more garbage collection, but should be relatively safe in terms of memory management.

Related

Updating an object stored in one Activity from another activity

I am creating an object called "AppEngine" inside my first activity. This AppEngine object stores and arrayList of Events, and begins with 2 events inside it.
From the first Activity I click a button which takes me to a second Activity in which I add an event object to the arrayList by using.
appEngine.getList.add(new Event)
When inside Activity 2, If I am to call appEngine.getList.size() the size is correctly returned as 3 and I can see the extra event.
When I switch back to Activity 2, I am calling appEngine.getList.size()however it only returns 2, and the extra event is not in there. How can i get the appEngine object to update?
save your array list in shared preference like this create a AppPreference Class:-
public class AppPreference {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static Set<AppEngine> getList(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getStringSet("AppEngineList", null);
}
public static void setList(Context ctx, ArrayList<AppEngine> value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
set.addAll(value);
mPrefsEditor.putStringSet("AppEngineList", set);
mPrefsEditor.commit();
}
}
set your value from first activity like this:-
setList(YourActivity.class, list);
and get your list from anywhere in you app:-
ArrayLis<AppEngine> list = AppPreference.getList(yourActivity.class);
If you only want the appEnginge object to persist during a single app session and not persist trough a complete app close/restart, then you should use a handler class.
EngineHandler.java:
public static class engineHandler {
public static appEnginge _appEngine;
}
and then just call
engineHandler._appEngine = _myAppengine;
engineHandler._appEngine.getList().add(new Event);
from your activity(s). The engineHandler will be accessible from any activity in your application.
You can use Singleton design Pattern.
You create one object from AppEnginRepository with eventList field and in your app you just get it and each time you want, you change it.
public class AppEnginRepository {
private List<Event> eventList;
private static final AppEnginRepository ourInstance = new AppEnginRepository();
public static AppEnginRepository getInstance() {
return ourInstance;
}
private AppEnginRepository() {
eventList = new ArrayList<>();
}
public List<Event> getEventList() {
return eventList;
}
public void setEventList(List<Event> eventList) {
this.eventList = eventList;
}
}
In your Activities
AppEnginRepository enginRepository=AppEnginRepository.getInstance();
List<Event> eventList=enginRepository.getEventList();
eventList.add(new Event());
int eventListSize=eventList.size();
It would be good to think each Activity is totally separated execution. Technically it's arguable, but it is good assumption to design cleaner and safer software.
Given assumption, there are several approaches to maintain data across Activities in an app.
As #Sandeep Malik's answer, use SharedPreference OS-given storage.
Similar to #Joachim Haglund's answer, use Singleton pattern to maintain an object in app.
Or, use small database like Realm.
Every approach has similar fashion; there should be an isolated and independent storage which is not belonged to one of Activity but belonged to ApplicationContext or underlying framework.

Android - right way to store a value for repeated use?

I have a service in my app that is always running but the global static variables seem to get reset when the phone is idle for a while (possibly the app is getting closed). Please let me know the optimal way to store a value for repeated use, maybe once in 2-5 mins.
Will using a SharedPreference cause high overhead if accessed once in 2-5 mins ?
Appreciate your help.
SharedPreference is best option.
public class AppPreference {
public static final String APP_NAME_KEY= "your_app_name";
public static final String SAMPLE_KEY = "sample";
public SharedPreferences preferences;
private SharedPreferences.Editor editor;
private String sample;
public AppPreference(Context context) {
preferences = context.getSharedPreferences(APP_NAME_KEY, Context.MODE_PRIVATE);
editor = preferences.edit();
}
public void setSample(String sample) {
this.sample= sample;
editor.putString(SAMPLE_KEY , this.sample);
editor.commit();
}
public String getSample() {
return preferences.getString(SAMPLE_KEY, null);
}
}
You can use Integer, Float, boolean values according to your requirement.

Is it safe to keep a static reference to a SharedPreferences and its Editor?

Im going to make something like:
private static SharedPreferences sharedPreferencesInstance;
public static SharedPreferences getSharedPreferences(final Context context){
if (context==null)
return sharedPreferencesInstance;
if (sharedPreferencesInstance == null)
sharedPreferencesInstance = context.getApplicationContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
return sharedPreferencesInstance;
}
private static SharedPreferences.Editor sharedPreferencesEditorInstance;
public static SharedPreferences.Editor getSharedPreferencesEditor(final Context context){
if (context==null)
return sharedPreferencesEditorInstance;
if (sharedPreferencesEditorInstance == null)
sharedPreferencesEditorInstance = context.getApplicationContext().getSharedPreferences("prefs", Context.MODE_PRIVATE).edit();
return sharedPreferencesEditorInstance;
}
but is it safe in meaning of Context leaks?
To answer the question authoritatively, it is safe to store the SharedPreferences instance as a static reference. According to the javadocs it is a singleton, so its source from getSharedPreferences is already a static reference.
It is not safe to store the SharedPreferences.Editor because it is possible two threads may be manipulating the same editor object at the same time. Granted, the damage this would cause is relatively minor if you happen to have already been doing it. Instead, get an instance of an editor in each editing method.
I highly recommend using a static reference to your Application object instead of passing in Context objects for every get. All instances of your Application class are singletons per process anyways, and passing around Context objects is usually bad practice because it tends to lead to memory leaks via reference holding, and is unnecessarily verbose.
Finally, to answer the unasked question if you should lazily-load or greedily-initialize the reference to your static SharedPreferences, you should lazily load in a static getter method. It may work to greedily-initialize a reference with final static SharedPreferences sReference = YourApplication.getInstance().getSharedPreferences() depending on the chain of class imports, but it would be too easy for the class loader to initialize the reference before the Application has already called onCreate (where you would initialize the YourApplication reference), causing a null-pointer exception. In summary:
class YourApplication {
private static YourApplication sInstance;
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static YourApplication get() {
return sInstance;
}
}
class YourPreferencesClass {
private static YourPreferencesClass sInstance;
private final SharedPreferences mPrefs;
public static YourPreferencesClass get() {
if (sInstance == null)
sInstance = new YourPreferencesClass();
return sInstance;
}
private final YourPreferencesClass() {
mPrefs = YourApplication.get().getSharedPreferences("Prefs", 0);
}
public void setValue(int value) {
mPrefs.edit().putInt("value", value).apply();
}
public int getValue() {
return mPrefs.getInt("value", 0);
}
}
You will then use your statically available preferences class as such:
YourPreferencesClass.get().setValue(1);
A final word about the thread-safety and memory observability. Some astute observers may notice that YourPreferencesClass.get() isn't synchronized, and hence dangerous because two threads may initialize two different objects. However, you can safely avoid synchronization. As I mentioned earlier, getSharedPreferences already returns a single static reference, so even in the extremely rare case of sInstance being set twice, the same underlying reference to SharedPreferences is used. Regarding the static instance of YourApplication.sInstance, it is also safe without synchronization or the volatile keyword. There are no user threads in your application running before YourApplication.onCreate, and therefore the happens-before relationship defined for newly created threads ensures that the static reference will be visible to all future threads that may access said reference.
I think it is safe. I always use a "KeyStoreController" with a static reference to a SharedPreferences object (singleton). I would suggest you to use an Application context instead of passing a context every time. This is an example of my code:
public class KeyStoreController{
private static KeyStoreController singleton = null;
private SharedPreferences preferences = null;
private KeyStoreController(Context c){
preferences = PreferenceManager.getDefaultSharedPreferences(c);
}
public static KeyStoreController getKeyStore(){
if( singleton == null){
singleton = new KeyStoreController(MainApplication.getContext());
}
return singleton;
}
public void setPreference(String key, Object value) {
// The SharedPreferences editor - must use commit() to submit changes
SharedPreferences.Editor editor = preferences.edit();
if(value instanceof Integer )
editor.putInt(key, ((Integer) value).intValue());
else if (value instanceof String)
editor.putString(key, (String)value);
else if (value instanceof Boolean)
editor.putBoolean(key, (Boolean)value);
else if (value instanceof Long)
editor.putLong(key, (Long)value);
editor.commit();
}
public int getInt(String key, int defaultValue) {
return preferences.getInt(key, defaultValue);
}
public String getString(String key, String defaultValue) {
return preferences.getString(key, defaultValue);
}
public boolean getBoolean(String key, boolean defaultValue) {
return preferences.getBoolean(key, defaultValue);
}
public long getLong(String key, long defaultValue) {
return preferences.getLong(key, defaultValue);
}
If you are passing around the Context it is best to be passing along an ApplicationContext. It might be easier if you just make a static ApplicationContext to reference and then just use the SharedPreferences when you need them from within your classes (if that approach works for you).
If you have the argument for the calls a Context then you shouldn't have to worry about leaks unless you are holding on to it.
But, I think that you will be just fine doing what you are doing conceptually.
Why not just create a static class and use it as a utility so you never have to keep a reference to your SharedPreferences at all. You also never have to initialize an instance of this class and can just call PreferencesUtil.getUserName(context) so long as you have a context to supply.
public static class PreferencesUtil{
private static final String USER_NAME_KEY = "uname";
public static void setUserName(String name, Context c){
SharedPreferences sharedPref = getPreferences(c);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(USER_NAME_KEY, name);
editor.commit();
}
public static String getUserName(Context c){
return getPreferences(c).getString(USER_NAME_KEY, "");
}
private SharedPreferences getPreferences(Context context){
return context.getPreferences(Context.MODE_PRIVATE);
}
}

Read shared preference when context is changed

I have a DialogView which stores settings in shared preferences. It is located in package A and i have another activity which is located in package B, which should be able to read these preferences.
So I created a wrapper class, which takes context and shared preference name and retrive these settings. When shared preferences are set at the first time everything works great, but when I change it, I got the same result, which was set at first time.
Problem is I save preference in one process and need to be able to read them in another.
So it seems like Context has changed and I am not able to retrive new context. What should I do to get up to-date shared preference?
Thank you on advance.
Please take a look at my wrapper class
public class PhotoAppWidgetSettingsProxy extends Proxy {
private final static String PREFERENCES_NAME = PhotoAppWidgetSettingsProxy.class.getName();
private final static int PREFERENCES_MODE = Context.MODE_PRIVATE;
private Context mCtx = null;
private SharedPreferences pref = null;
private SharedPreferences.Editor editor = null;
public PhotoAppWidgetSettingsProxy(String name, Context context) {
super(name, context);
mCtx = context;
pref = context.getSharedPreferences(PREFERENCES_NAME, PREFERENCES_MODE);
editor = pref.edit();
}
private final static String FRAME = "FRAME";
/**
* Sets selected frame mode
* #param frame id
*/
public void setFrameMode(int frameId){
editor.putInt(FRAME, frameId);
Log.d(PREFERENCES_NAME, "SET MODE="+frameId);
boolean success = editor.commit();
Log.d(PREFERENCES_NAME, "SET MODE="+success);
}
/**
* Gets selected frame mode
* #return frame id
*/
public int getFrameMode(){
Log.d(PREFERENCES_NAME, "GET MODE="+pref.getInt(FRAME, 0));
return pref.getInt(FRAME, 0);
}
SOLVED:
private final static int PREFERENCES_MODE = Context.MODE_MULTI_PROCESS;
private final static int PREFERENCES_MODE = Context.MODE_MULTI_PROCESS;
When accessing shared preferences/values, I have found it useful to write a CustomApplication class extending Application. I can place any necessary fields/methods in there, and easily acquire them from any of the other Android classes by using:
CustomApplication app = (CustomApplication) getApplication();
int x = app.getX();
Does that help you at all?

Accessing SharedPreferences through static methods

I have some information stored as SharedPreferences. I need to access that information from outsite an Activity (in from a domain model class). So I created a static method in an Activity which I only use to get the shared preferences.
This is giving me some problems, since apparently it is not possible to call the method "getSharedPreferences" from a static method.
Here's the message eclipse is giving me:
Cannot make a static reference to the non-static method
getSharedPreferences(String, int) from the type ContextWrapper
I tried to work around this by using an Activity instance, like this:
public static SharedPreferences getSharedPreferences () {
Activity act = new Activity();
return act.getSharedPreferences("FILE", 0);
}
This code gives a null point exception.
Is there a work-around? Am I going into an android-code-smell by trying to do this?
Thanks in advance.
Cristian's answer is good, but if you want to be able to access your shared preferences from everywhere the right way would be:
Create a subclass of Application, e.g. public class MyApp extends Application {...
Set the android:name attribute of your <application> tag in the AndroidManifest.xml to point to your new class, e.g. android:name="MyApp" (so the class is recognized by Android)
In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getApp(). You then can use this method later to get a context of your application and therefore get your shared preferences. :-)
That's because in this case, act is an object that you just create. You have to let Android do that for you; getSharedPreferences() is a method of Context, (Activity, Service and other classes extends from Context). So, you have to make your choice:
If the method is inside an activity or other kind of context:
getApplicationContext().getSharedPreferences("foo", 0);
If the method is outside an activity or other kind of context:
// you have to pass the context to it. In your case:
// this is inside a public class
public static SharedPreferences getSharedPreferences (Context ctxt) {
return ctxt.getSharedPreferences("FILE", 0);
}
// and, this is in your activity
YourClass.this.getSharedPreferences(YourClass.this.getApplicationContext());
I had a similar problem and I solved it by simply passing the current context to the static function:
public static void LoadData(Context context)
{
SharedPreferences SaveData = context.getSharedPreferences(FILENAME, MODE_PRIVATE);
Variable = SaveData.getInt("Variable", 0);
Variable1 = SaveData.getInt("Variable1", 0);
Variable2 = SaveData.getInt("Variable2", 0);
}
Since you are calling from outside of an activity, you'll need to save the context:
public static Context context;
And inside OnCreate:
context = this;
Storing the context as a static variable, can cause problems because when the class is destroyed so are the static variables. This sometimes happens when the app is interrupted and becomes low on memory. Just make sure that the context is always set before you attempt to use it even when the class setting the context is randomly destroyed.
Here's a better alternative to storing your shared preferences in static fields.
Similar to what has been suggested here, create a class that extends Application
Make the constructor for your class take Context as a parameter.
Use your context to get shared preferences and store them in private variables.
Create public variables to return the retrieved data.
e.g
public class UserInfo extends Application{
private String SAVED_USERID;
private String SAVED_USERNAME;
public UserInfo(Context context) {
SharedPreferences prefs = context.getSharedPreferences(FILE, MODE_PRIVATE);
SAVED_USERNAME = prefs.getString("UserName", null);
SAVED_USERID = prefs.getString("UserID", null);
}
public String getSavedUserName() {
return SAVED_USERNAME;
}
public String getSavedUserID() {
return SAVED_USERID;
}
}
usage in your activity
UserInfo user = new UserInfo(this.getApplicationContext());
String SAVED_USERNAME = user.getSavedUserName();
String SAVED_USERID = user.getSavedUserID();
I had the same need - some of my preferences need to be accessed often, and efficiently. I also imagine that reading and writing a string from SharedPreferences is slightly slower than getting and setting a static variable (but likely to an insignificant degree). I also just kind of got used to using static fields, retrieving Preference values only at startup, and saving them on close.
I didn't love my options for keeping static references to the SharedPreferences/contexts directly, but so far this workaround has sufficed.
My solution:
Create a Settings class with all the static variables you need.
When the application initializes, retrieve SharedPreferences fields and immediately set all Settings fields (I call a "loadSharedPrefs()" method at the end of MainActivity's onCreate method).
In the SettingsActivity's preferenceChangeListener's initialization, set the appropriate static field in the Settings class. (I call a "setAppropriateSetting(key, value)" method at the beginning of SettingsActivity's onPreferenceChange()).
Use your static preferences wherever, whenever!
public static String getPreferenceValue(Context context) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
String key = context.getString(R.string.pref_key);
String defaultVal = context.getString(R.string.pref_default);
return sharedPreferences.getString(key,defaulVal);
}

Categories

Resources