Tags
Android
Asked 1 years ago
26 Apr 2023
Views 294
sandip

sandip posted

how to manage Session in Android?

explain me Session Management in Android with Example
jignesh

jignesh
answered May 1 '23 00:00

one can manage sessions by using SharedPreferences . SharedPreferences is a lightweight key-value storage system that allows you to store and retrieve simple data in your application .

Here are the steps to manage sessions using SharedPreferences in Android:

Create a SharedPreferences object : To create a SharedPreferences object, you need to call the getSharedPreferences() method and pass in a name for your preferences file and a mode. For example:


SharedPreferences preferences = getSharedPreferences("my_preferences", MODE_PRIVATE);


Save data to SharedPreferences : To save data to SharedPreferences, you can use the edit() method to get a SharedPreferences.Editor object, and then use its putXXX() methods to store data. For example:

SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", "johndoe");
editor.putInt("user_id", 12345);
editor.apply();

In this example, we're storing a username and user ID in SharedPreferences.

Retrieve data from SharedPreferences : To retrieve data from SharedPreferences, you can use the getXXX() methods of the SharedPreferences object. For example:

String username = preferences.getString("username", "");
int userId = preferences.getInt("user_id", 0);

In this example, we're retrieving the stored username and user ID.

Clear data from SharedPreferences : To clear data from SharedPreferences, you can use the clear() method of the SharedPreferences.Editor object. For example:

editor.clear();
editor.apply();


This will remove all data stored in the preferences file.

By using SharedPreferences , you can easily manage sessions in your Android application . You can store data such as login credentials or user preferences, and retrieve them later when needed.
Post Answer