SharedPreferences and Application class - android

I have many shared preference for my app (mostly relating to color customization) and I'm unsure what the best method is to store/use them at runtime.
Currently I am doing something like this (with more or less preferences depending on the view) in every activity/fragment:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
int buttonbg = settings.getInt("buttonmenu_bg", 0);
int buttontxt = settings.getInt("buttonmenu_txt", 0);
int headerclr = settings.getInt("header", 0);
And then using those to set the various colors in the display. This seems like a lot of overhead to have to call the PreferenceManager each time and go through all that.
So I started looking at creating an application class, reading the preferences in once and using static variables from the application class in the activities/fragment to set the display.
My question is, are there any drawbacks or gotchas to doing this that I should consider before I venture further down the Application class path?

If you are not using so many static variables so this may not affect your application.But the problem with static variable may arise when your app goes to background and the app running on front requires memory so it may clear your static data,so when you will go to your app you may find nothing (null) in place of static data.

The purpose of the Application class is to store global application state or data (in memory of course), so your approach is correct. I've used it multiple times and it works like a charm.
What I usually do is to create a Map member variable and provide methods for getting and putting values into it, looks like this:
package com.test;
...
...
public class MyApp extends Application{
private Map<String, Object> mData;
#Override
public void onCreate() {
super.onCreate();
mData = new HashMap<String, Object>();
}
public Object get(String key){
return mData.get(key);
}
public void put(String key,Object value){
mData.put(key, value);
}
}
Then from my activities, I just do ((MyApp) getApplication()).get("key") or ((MyApp) getApplication()).put("key",object). Also, don't forget to set the android:name attribute in your manifest file, under the application tag:
<application
...
...
android:name="com.test.MyApp">
</application>

Is there any particular reason why you are not setting the display colors in res/values/styles.xml?

Related

best practice to share global variables between activities

I'm a bit confusing on how to share global variables between activities in an android project that considered safe.
What is the best practice to do that? Extends Application class or make a custom singleton class?
An help is apprecciate, thanks in advance.
The problem with storing something in the application class is you cannot count on an activity being resumed from the same instance of the application object. For example an activity can be paused, the application killed (due to memory) along with any changes you made to object in the instance, and then the activity resumed with a new application instance.
Here is a very good BLOG post explaining how data stored in the application class can be lost:
http://www.developerphil.com/dont-store-data-in-the-application-object
I am not sure this is the very "Best" practice, but I think this is a good solution
I have a PersistData class holds application wide "globals". I use Dagger to inject instances of this singleton into any class that requires these variables.
The basic process it this:
When I save a value in this object via something like:
mPersistData.saveEmailId("me#example.com");
I first write it to an entry in SharedPreferences
I then save it to a member variable
In the constructor for the class, I initialize the member variables by reading them from SharedPreferences.
This way reads for the variable are "cached", ie they don't need to be read from SharedPreferences, and if the application is ever killed and restarted the member variables have the correct values. If you just hold the values in the application class, when the application is restarted the member variables will be invalid (not what you expect or even null).
Here is an example:
public class PersistData {
private String email;
public PersistData(MyApp app) {
mApp = app;
email = readEmailId();
}
public void saveEmailId(String emailToSave) {
writeEmailId(emailToSave);
email = emailToSave;
}
private void writeEmailId(String emailId) {
generalSettingsFileEditor.putString("USER_ID", emailId);
generalSettingsFileEditor.commit();
}
public String readEmailId() {
String emaiId = generalSettingsFile.getString("USER_ID","");
return(emaiId);
}
public String getEmail() {
return email;
}
}
In my application Dagger module I have this:
#Provides #Singleton
public PersistData providePersistData () {
System.out.println(String.format("mApp = %s", mApp));
return new PersistData(mApp);
}
Then whenever I need to access any of these variables I inject the singleton as so:
public class HomePresenter {
#Inject
PersistData mPersistData;
...
mPersistData.saveEmailId("me#example.com");
myEmail = mPersistData.getEmailId();
...
}
What is the best practice to do that? Extends Application class or
make a custom singleton class?
Think twice whether those variables are really global and they have to be shared between activities.
If the answer to first question is 'yes', then the best place would be to store them in Application.
You can implement a singleton too, but 1) it's slightly more difficult to test and b) if your global variables require Context, then again Application instance would fit the best.

Store a string until the application gets "force stopped"

I need a way to store a json-string as for as long as the application is alive.
So to put this into other words :)
If the application changes orientation or gets paused or stopped i need to store my value/string..
But if the application gets forced killed for some reason I want the value to be removed/droped
Im trying to create a custom history-handler.. and this history handler is suppoed to keep history of actions with in my application for as long as the application process is actually running, but as soon as the process gets killed I need the history to get erased as well.
I have tried to store the value/string as a SharedPrefernce, and to simply remove it once isFinishing()== true
I have also tried using the onDestroy as well.. but there seems to be no "beforeProcessKilled"-event to listen for.. so maybe there is another option than using the SharedPreferences?
Thanks in advance!
Use a simple Java static data member. That value will live until the process is terminated, for whatever reason.
It's my way, maybe not the best.
You can create a class named "Global" or other...
Then declare inside something like this, some "static" variables :
public class Global_variables {
public static JSONArray test;
public static String test1;
}
Then, in your activity or other, import "Global_variables" and get your String or other like this:
String IwantTostore = Global_variable.test1;
If you change orientation, your Global_variable.test1 keep alive ;)
Hope this help
I usually do something like this
public class Globals extends Application {
private String jsonString;
public void jsonString(String string) {
jsonString = string;
}
public String jsonString() {
return jsonString;
}
}
then access it with something like
Globals myGlobal = (Globals)getApplication();
// get json string
String json = myGlobal.jsonString();
so on...

Why is Context "becoming" null on Application class?

Problem using Application
I'm rewriting an app (first 'version' had little-to-nothing in terms of analysis and it ended up piling a bunch of problems I wanted to get rid of) and I'm bumping my head against a problem that never showed up in the first version.
Thing is: I have a Class for geographical data. It just supplies String arrays that I can tuck into spinners adapters. Since I used a values xml file, the class needs access to Context to get the proper resources.
Since I use this geographical data in several points of the app, I thought I could create a Class to extend Application and, in onCreate, instantiate the Geography Class, I thought it would be more efficient to load it just once and use it as many times as I wanted. This worked on my first version:
This is MyApplication class
private static Context context;
public void onCreate(){
super.onCreate();
MyApplication.context = getApplicationContext();
geografiaEspana = GeographyClass.getInstance(context);
}
public static GeographyClass getGeografiaEspana() {
if(ctx==null){
Log.w("TAPABOOK", "Tapabook.context nulo");
}
if (geografiaEspana==null){
Log.w("TAPABOOK", "Tapabook.geografiaEspana nula, instanciando");
geografiaEspana = GeographyClass.getInstance(ctx);
}
Log.i("TAPABOOK", "Tapabook.geografiaEspana instanciada");
return geografiaEspana;
}
And this is my GeographyClass
private static GeographyClass instance = null;
public static GeographySpain getInstance(Context context){
if(instance== null){
instance = new GeographySpain(context);
}
return instance;
}
public GeographySpain(Context context){
Resources res = context.getResources();
// load resources data
}
This worked, as I said, ok in my first version. However, in my new version I'm getting a NullPointerException on this line "Resources res = context.getResources();" I've checked and it turns out that the context I'm supplying it's null... And I don't get to understand why or what I'm doing wrong
Ok, I solved it (I'd swear I already commented on this, but since it's gone...).
Thing is, I'm not used to use Application classes and I had forgotten to declare MyApplication in the Manifest file. Noob mistake. As soon as I declared it, the app ran OK

Solution to access global data from everywhere - efficiently

I need to find a solution that holds and accesses large chunks of complex global data and methods. It has to be accessible from within activities and normal instance variables of various data classes.
This is how I have done it. I would just like to know if there is anything wrong with it or if there is a better/cleaner way.
First I extend Application like recommended many times...
public class MainDataManager extends Application{
public ... large chunks of data in arrays, lists, sets,....
//static variable for singleton access from within instance variables of other classes
public static MainDataManager mainDataManager;
//create and init the global data, and store it in the static variable of the class
#Override
public void onCreate() {
super.onCreate();
//in case it should get called more than once for any reason
if (mainDataManager == null) {
init();
mainDataManager = this;
}
}
Now accessing it from within activities like everywhere recommended...
MainDataManager mainDataManager = (MainDataManager)getApplicationContext();
And since I need to access it from normal instances of data classes ...
public class MyDataClass {
public MainDataManager mainDataManager;
public String name;
public MyDataClass(String namex) {
this.name = namex;
//this is why I defined the static variable within MainDataManager, so
//one has access to it from within the instance of MyDataClass
this.mainDataManager = MainDataManager.mainDataManager;
}
public void examplesForAccessing() {
//some examples on how to access the global data structure and associated methods
mainDataManager.someMethodAccess();
xyz = mainDataManager.someDataAccess;
mainDataManager.someIndirectMethodAccess.clear();
mainDataManager.someOtherData = false;
}
}
Since I have not done this so far, I would like to know if there is anything wrong with this. Memory, efficiency, ...
Thanks very much!
May I add a little sidenote?
I could also have just used a class MainDataClass and access by MainDataClass.var or MainDataClass.method(). Is there any REAL disadvantage?
Is the data in both cases held in heap/stack?
You haven't given much detail about your "large chunks of data" but keep in mind that the onCreate method is the first things that runs when your application is starting and it runs on the main/UI thread. This means that if you do long tasks in your init() method your UX will be poor, not to mention that you are risking an ANR exception.
The solution for that is simple:
Keep your onCreate short
Create a BG thread and use it to run all initialization code
Show a "Splash"/"Welcome" screen with the a proper progressbar while the BG thread is running.

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