This can be done in 2 ways. One is storing them in a global variables and second is storing the data in SharedPreferences. The problem with storing data in global variable is data will be lost once user closes the application, but storing the data in SharedPreferences will be persistent even though user closes it.
1. About SharedPreferences
SharedPreferences are used in android to store some data presistently(i.e. after closing of application, it will persist).If you want to store few amount of data then you can go for SharedPreferences rather than going for SQLite and all. In that case Shared Preferences are useful.
In this post, I give a simple example about using it to manage user login/logout.
1. Creating Project
To keep everything simple, declaring login informations (user name and password) in ConstantString.java:
SharedPreferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences , you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences:
pref = this.context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);We can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will receive it in an editor object. It's syntax like:
Editor editor = sharedpreferences.edit(); editor.putString("key", "value"); editor.commit();In this project, I make a SessionManager file and define a SharedPreferences object in it. Source code for most important file:
For using SharedPreferences in whole application, we must initialize/retreive it with ApplicationContext:
sessionManager = new SessionManager(getApplicationContext());You will see above line in all Activities then.
In LoginActivity, checking input entered, if it failed, app show error notice by Toast and if it pass, we'll go to HomeActivity immediately. Code for LoginActiviy.java:
HomeActivity: on include some TextViews to display user informations by retreive from SharedPreferences:
And it layout (xml):