This question already has an answer here:
- Android global variable 14 answers
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 store it in a SharedPreferences, and create a sharedpreferenceHelper class to retrieve/store it.
Application
and putting it there) is ok.SharedPreferences
is probably the easiest to use.See also this Stack Overflow question: What's the best way to share data between activities?
Its always better to store values which you want to use multiple times in one of the following ways:-
You can create the global variable in android by declaring them in the class which extend the
Application
class.Something like this.
MainActivity.java
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