Back to Top

How to Manage Session in Android App

Updated 16 July 2021

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.

Start your headless eCommerce
Find out More
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.commit(); // commit changes

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home