Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5554

How to Manage Session in Android App

$
0
0

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. 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

Viewing all articles
Browse latest Browse all 5554

Trending Articles