There are two ways to manage sessions in android Applications.
1. Global Variable.
2. Shared Preference.
Both will work but there is a problem with Global variable i.e Global variable got destroyed, once your application is closed.
For this problem only, Shared Preference is introduced, its value persist even if you close your application. Shared Preference is a key value pair.
Below you can see how to use Shared Preference step by step.
1. Initialization
To add value to your Shared Preference object you need to edit its object with an editor.
SharedPreferences shared = getApplicationContext().getSharedPreferences("YourSessionName", MODE_PRIVATE); Editor editor = shared.edit();
2. Set Data
You can set any type of data using provided following functions.
editor.putBoolean("key", true); // Storing boolean - true/false editor.putString("key", "value"); // Storing string value editor.putInt("key", "value"); // Storing integer value editor.putFloat("key", "value"); // Storing float value editor.putLong("key", "value"); // Storing long value editor.commit(); // commit changes
3. Get Data
You can get data in the same way as you set it, without use of editor.
SharedPreferences shared = getSharedPreferences("YourSessionName", MODE_PRIVATE); Boolean variable = (shared.getBoolean("key",false)); String variable = shared.getString("key", ""); Int variable = shared.getInt("key",0); Float variable = shared.getFloat("key", 0.0); Long variable = shared.getLong("key", 0);
the second parameter is the default value that it will return if the key won’t exist.
4. Edit Shared Preference
you can clear the whole SharedPreference object at once or remove single key value pair.
SharedPreferences shared = getSharedPreferences("YourSessionName", MODE_PRIVATE); editor = shared.edit(); editor.remove("name"); // will delete key name editor.commit(); // commit changes To empty SharedPreference object at once editor.clear(); editor.commit(); // commit changes
Be the first to comment.