Global static variable or shared preference android - java

My Android project need share a List<Right> rights between Activities. The value of this list is initiated in LoginActivity. In other Activity, i use this list to check right of user (if user has a correspondence right, app will show correspondence tab or do something else). The problem i meet is how to store List<Right> rights in my Android application. I have read many Post and people use Gson and Flexjson to change this list to String and use SharedPreferences.Editor putString (String key,String value) to store in SharedPreferences. In other Activity, use preferences.getString("girl_heart_key", "DEFAULT"); to get String and Deserialize it to List<Right> rights. But i think we can use a global static variable:
public static List<RightObject>rights = new ArrayList<RightObject>();
to share List<RightObject>rights between Activities.
My question is: can we use global static variable to replace SharePrefrence in this case? and Is there any risk( about performance, security or memory) ?

NO, it's not recommended to do it.
global static variable has same lifetime as your Application, data will be destroyed once Application is finished. SharedPreference on the other hand can persist the data until user has clear the storage/cache of your app through app settings.
The better approach is to have a Repository that can be shared as a DataSource for your application.
In case you accidentally have a static reference to a Context, than there will be a memory leak.
see more Android : Static Fields and Memory Leaks

Related

Prevent class from unload, java

In my Android App I have a static class to share some variables and functions within the whole application.
some variables from this class are initiated in other Activities (once, for example, user select something from the grid view, then I store its selection in this static class to use it later in another activity)
Everything was fine, but it looks like that after some period of inactivity of the App (once it stays in the Background), this static class is destroyed and then re-initialized with default values, which are "wrong", let's say.
Or, probably, the whole app is disloaded, and after I call it back, it restores the last activity which is trying to access some variables but they are re-initiaed
It there any way to prevent class from re-initialization or keep the static values or to keep these values somehow else and restore them once activity is re-created?..
Thanks a lot!
Instead of looking for ways (or rather hacks) to stop re-initialisation of your classes or storing the variables in a static class I would rather suggest you to store the state of your app in local storages like Shared Preferences or the SQLite DB.
The advantage of this would be you can access this variables in any part of your app and secondly you will get rid of those static classes and variables which are the main culprit of Memory leaks and ANRs.
I think sharedPreference is the perfect alternative for you. It helps to store your data locally.

When to use static variable and sharedpreference in android

When to use static variable and sharedpreference in android.
Which is the best to use. Can anyone explain with example.
Thanks in advance.
You can use static when there is not huge amount of data in the application.
sharedpreference can be used if the data is more also and can be stored and retrieved as and when it is required.
If you stored a value in a static variable and kill the application from recent(pressing Home button and clean all the running apps) then your value kept in static variable will be lost. But if you saved it in shared preference then you can read the saved value whether the application is killed from recent or not.
Shared Preferences is used to store and retrieved values.
There are plenty of link available :
1.Shared Preferences
2.Shared Preferences

How to create a global variable in android? [duplicate]

This question already has answers here:
Android global variable
(14 answers)
Closed 8 years ago.
In my android application I need a place for putting the variable member id .
The problem is , it is getting from the online API and I need to find a way to store / retrieve it
I have tried to put it in a custom class , but the problem is , it will lose if I kill the activity, I have also know that there is a way to extends the application.
So I would like to know what is the best way to store global variable?
I have to implment:
Save the variable on onSaveState
Save it on sharepref
Save it manually
Retrieve it manually
Thanks
Update:
Thanks for reply. If I have just 3 variable (simple data e.g. a boolean , a phrase ), and I need it after app restart , should I simply use share pref to store it? What is the drawback of it? e.g. Will it harmful to the performance? thanks
You can create the global variable in android by declaring them in the class which extend the Application class.
Something like this.
class MyAppApplication extends Application {
private String mGlobalVarValue;
public String getGlobalVarValue() {
return mGlobalVarValue;
}
public void setGlobalVarValue(String str) {
mGlobalVarValue = str;
}
}
MainActivity.java
class MainActivity extends Activity {
#Override
public void onCreate(Bundle b){
...
MyAppApplication mApp = ((MyAppApplication)getApplicationContext());
String globalVarValue = mApp.getGlobalVarValue();
...
}
}
Update
This hold the value until your application is not destroyed. If you want to keep your values save even after your application instance destroy
then you can use the SharedPreferences best way to do this.
Learn about the SharedPrefernces from here : http://developer.android.com/reference/android/content/SharedPreferences.html
If you need a global variable, which is shared between multiple activities and survives their lifecycle changes, but is otherwise not persisted and would not survive an application restart, the method suggested in the first answer (extending Application and putting it there) is ok.
If you need a persisted global setting, which should also survive an application restart, then you should use one of the other methods suggested. SharedPreferences is probably the easiest to use.
See also this Stack Overflow question: What's the best way to share data between activities?
You can store it in a SharedPreferences, and create a sharedpreferenceHelper class to retrieve/store it.
Its always better to store values which you want to use multiple times in one of the following ways:-
Shared Preferences
Singleton classes
Write it to a file
SQLite Database
Store on the web-server

What are the PreferenceManager and SharedPreference classes used for in Android?

I've come across two classes being used in a tutorial on splash screens PreferenceManager and SharedPreferences. I didn't gain a great deal of knowledge about them from the tutorial though.
So can someone explain to me what both classes do or are used for?
From the Android Developer site:
PreferenceManager:
Used to help create Preference hierarchies from activities or XML.
SharedPreferences:
Interface for accessing and modifying preference data returned by
getSharedPreferences(String, int). For any particular set of
preferences, there is a single instance of this class that all clients
share.
Put simply, PreferenceManager is normally used when you want to create a PreferenceActivity or load in some Preferences from an .xml file in your application with default values, and holds it's own referenced to SharedPreferences.
SharedPreferences is where you handle the storing and retrieving of key/value pairs that make up your preferences. So you can add variables with keys to retrieve the data later. This feeds into the PreferenceManager which can handle adding default values and setting up the default SharedPreferences.
You can use SharedPreferences throughout your application without needing to use PreferenceManager, but the opposite isn't strictly true.
Further reading:
PreferenceActivity (also PreferenceFragment), which uses
PreferenceManager in the examples.
Android Data Storage which
uses SharedPreferences (as well as other options).
Vogella article on Android Persistence.
StackOverflow issue on using SharedPreferences correctly.
Preferences is an Android lightweight mechanism to store and retrieve pairs
of primitive data types (also called Maps, and Associative Arrays).
In each entry of the form the key is a string and the value must be a primitive data type.
WHEN WE NEED THEM:
PREFERENCES are typically used to keep state information and shared data
among several activities of an application.
Shared Preferences is the storage, in android, that you can use to store some basic things related to functionality, users' customization or its profile.
Suppose you want to save user's name in your app for future purposes. You cant save such a little thing in database, So you better keep it saved in your Preferences. Preferences is just like a file , from which you can retrieve value anytime in application's lifetime in a KEY-VALUE pair manner.
Take another example, If you use whatsapp, we have a wallpaper option there. How the application knows which image serves as wall-paper for you whenever you open your whatsapp. This information is stored in preferences. Whenever you clear data for any app, preferences are deleted.
HOW TO USE THESE PREFERENCES :
final int mode = Activity.MODE_PRIVATE;
final String MYPREFS = "MyPreferences_001";
// create a reference to the shared preferences object
SharedPreferences mySharedPreferences;
// obtain an editor to add data to my SharedPreferences object
SharedPreferences.Editor myEditor;
mySharedPreferences = getSharedPreferences(MYPREFS, 0);
// using this instance you can get any value saved.
mySharedPreferences.getInt("backColor",Color.BLACK); // default value is BLACK set here
EDITING SHARED PREFERENCES :
myEditor = mySharedPreferences.edit();
//edit and commit
myEditor.putString("backColor", Color.RED);
myEditor.commit() //very imp.
As explained Artoo Detoo... Sharedpreferences kinda works like sessions in web development. you can use them to pass values from one activity to another and it stays that way as far as the app is in use except otherwise changed..
it is also use to user value (either after login or registration of the user). thats how much i can talk about it
SharedPreference APIs are used to save key-value pairs. They store them in files and are private or public based on the mode you instantiate the SharedPreference object. They are used to store a small set of key-value pairs. This key here is of type String and the value can be any primitive type.
PreferenceManager is part of the Preference APIs. Preference API allows you to define a complete settings UI. This settings UI is an XML layout. You use a PreferenceManager to manage this Preference object's tree. It uses the SharedPreference APIs to store the various settings a user might change using that graphical layout you created.
Reference - "Android Docs Training"

Is putExtra the only way of passing data to a new Activity?

I have created a SettingsActivity for my app. In this Activity I am using the SharedPreferences class to do handle the user editable preferences.
While setting up the SharedPreferences, I have to load them in the onCreate of my main activity and then again in the SettingsActivity. The probably was that both calls to the getXXXX() methods require defaults and I figured that it would not be good to hard-code the default values into both places because I would imagine it would be problematic in the future if I ever changed them.
Which is the best/most popular (or accepted standard) of doing this?
Create a global variables class in which I import into each activity and define my default constants in there?
Use putExtra and getExtra to pass the data from the main activity to the settings activity?
Any other suggestions?
I think Squonk has a good answer, but if you're looking for an alternative, consider creating a Settings class with all of your settings as members. It could have a static method like loadFromPreferences(Context) that would return a Settings object constructed from SharedPreferences, using whatever defaults you need. It could also have a saveSettings(Context) method to save your edits. Hope that helps.
Personally, in this situation, I'd put the default values in a resource file. In that way there's no need to use a global variables class or a helper class. Android resources already do that for you.
See:
Providing resources
More resource types
Instead of using a class with static values why dont you extend the Application class which will always live when the application's process lives. you can keep shared methods and variables in it
I would highly recommend opening the SharedPreference in the onCreate of both activities. Every time I've tried to use global variables, the values disappear in a way that's difficult to detect and fix. Activities are destroyed when they are closed. Services can be removed from memory at any time. The application context will be destroyed if your services are sleeping and don't have activities in memory.
That being said, putting a variable in the application context is probably the best place. Create a class that extends Application and set AndroidManifest.xml to use this. Just don't expect the value to be there if you try to use it from services or broadcast receivers.
Also, unless you're having problems with the activities loading too slowly, you're better off spending time on features than optimization.
You can declare objects as public static and reference them from another class. ActivityA:
public static int testIntegerA = 42;
Intent intentInteger = new Intent(getActivityContext(), ActivityB.class);
intentInteger.putExtra("INTENT_EXTRA", testIntegerA);
startActivity(intentInteger);
ActivityB:
public static int intentInt, staticInt;
staticInt = ActivityA.testIntegerA;
intentInt = getIntent().getExtras().getInt("INTENT_EXTRA");
Now both intentInt and staticInt equal 42;

Categories