There are plenty of options for storing data while switching between activities, I'll list a couple of them here,
The first option is used when the values you want to store are key value pairs, and not complex objects. Sometimes people store complex objects by converting the objects to json string.
But sqlite is the preferred way to store complex objects especially with an ORM framework like greenDao, ORMlite etc. as you can directly store and retrieve java objects to and from the sqlite DB using these libraries.
Sharedpreference storage saves key value pairs in files, you can provide the MODE
for these files, if you specify private
mode then the file will only be accessible to your application. If you want to make the file accessible to other applications you need to specify as public
.
Sqlite on the other hand is a lite version of SQL based database storage designed specially for mobile devices. They are supposed to be faster and a lighter version of SQL used in servers.
I'll explain here how you can use shared preferences for your particular situation
SharedPreference
First you can create a sharedPreferencefile using a context object like so
SharedPreferences mySharedPref =
context.getSharedPreferences(PREFERENCE_FILE_NAME, Context.MODE_PRIVATE);
Here while creating you specify the ACCESS MODE
for the file.
Next in order to store values in this file you get a SharedPrefences.Editor
object for the file by calling the edit()
function on the sharedPreference object.
SharedPreferences.Editor editor = mySharedPref.edit();
Now you can add your int a = 25
key value pair into the editor like so.
editor.putInt("a", a);
Then you need to call the apply()
function in order to write to file.
editor.apply();
Then to retrieve all you need to do is call getInt() function on the sharedPreference object.
SharedPreferences mySharedPref = context.getSharedPreferences(PREFERENCE_FILE_NAME, Context.MODE_PRIVATE);
mySharedPref.getInt("a",0);
The 2nd argument in getInt()
function is a default value in case there was no value for the key "a" in the file.
So what you can do is store the value of a in a sharedpreffile in the onStop()
of your activity and retrieve it again in the onStart()
of your activity