Android allows storing data in a number of formats. But, we do android user session management using Shared Preferences, just because of shared preferences works on the Key-Pair basis and respond fast.
The session is useful when you want to store user data globally throughout the application. This can be done in two ways. One is storing them in global variables and second is storing the data in shared preferences.
The problem with storing data in the global variable is data will be lost once the user closes the application. But storing the data in shared preferences will be persistent even though the user closes the application.
Android Shared Preferences Overview
Android stores Shared Preferences settings as an XML file in the shared_prefs folder. SharedPreferences is application-specific. i.e. the data is lost on performing one of the following options:
- on uninstalling the application
- on clearing the application data (through Settings>>Apps)
To get access to the preferences, we have three APIs to choose from:
- getPreferences(): used from within your Activity, to access activity-specific preferences
- getSharedPreferences(): used from within your Activity (or other application Context), to access application-level preferences
- getDefaultSharedPreferences(): used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framework
getSharedPreferences (String PREFS_NAME, int mode)
- PREFS_NAME is the name of the file.
- MODE is the operating mode.
Following are the operating modes applicable:
In the above syntax, The first parameter is the key and the second parameter is the MODE. Apart from private, there are other modes available that are listed below:
- MODE_PRIVATE: the default mode, where the created file can only be accessed by the calling application.
- MODE_WORLD_READABLE: This mode allows other applications to read the preferences.
- MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous, and likely to cause security holes in applications.
- MODE_MULTI_PROCESS: This method will check for modification of preferences even if the shared preference instance has already been loaded.
- MODE_APPEND: This will append the new preferences with the already existing preferences.
- MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write-ahead logging by default.
Must see: Autofit grid layout Recyclerview
Initialization
Shared preferences can be fetched using the getSharedPreferences() method. We need an editor to edit and save the changes in shared preferences. The following code can be used to get the shared preferences.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
Storing Data
All the primitive data types like booleans, floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared preferences.
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.apply(); // commit changes
Retrieving Data
Data can be retrieved from saved preferences by calling getString() as follows:
pref.getBoolean("key_name", null); // getting boolean
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
Clearing or Deleting Data
If you want to delete from shared preferences you can call remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear()
editor.remove("name"); // will delete key name
editor.remove("phone"); // will delete key phone
editor.apply(); // commit changes
Must see: Add drawer layout with an event listener in android
User Session Management using Shared Preferences
Session Manager
In this file, all information regarding session related functions in one class to make them available in all activities. Create a new class named SessionManager.java and add the following lines of code.
import android.content.Context;
import android.content.SharedPreferences;
public class SessionManager {
private static String TAG = "SessionManager";
private static SessionManager sInstance;
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor sharedPreferencesEditor;
private SessionManager(Context context) {
if(sharedPreferences == null){
sharedPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
}
}
public static synchronized SessionManager getInstance(Context context) {
if(sInstance == null) sInstance = new SessionManager(context);
return sInstance;
}
public static boolean exist(String key) {
try {
if (key != null && sharedPreferences != null && sharedPreferences.contains(key)) {
//Log.d(TAG, "sharedPreferencesEditor key : " + key + " exists");
return true;
} else {
//Log.d(TAG, "sharedPreferencesEditor key : " + key + " NOT exists");
return false;
}
}catch (Exception e){e.printStackTrace();}
return false;
}
public static void removeKey(String key) {
try {
if(sharedPreferences != null && key != null) {
sharedPreferencesEditor = sharedPreferences.edit();
if (sharedPreferences.contains(key)) {
sharedPreferencesEditor.remove(key);
sharedPreferencesEditor.apply();
}
}
}catch (Exception e){e.printStackTrace();}
}
public static void removeAll() {
try {
if(sharedPreferences != null) {
String email_id = null;
String email_pwd = null;
if (exist(AppController.REMEMBER_ME) && getBoolean(AppController.REMEMBER_ME)) {
email_id = getString(AppController.CUSTOMER_EMAIL_ID);
email_pwd = getString(AppController.CUSTOMER_PASSWORD_TEXT);
}
sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.clear();
sharedPreferencesEditor.apply();
if(email_id != null && email_pwd != null){
setBoolean(AppController.REMEMBER_ME, true);
setString(AppController.CUSTOMER_EMAIL_ID, email_id);
setString(AppController.CUSTOMER_PASSWORD_TEXT, email_pwd);
}
}
}catch (Exception e){e.printStackTrace();}
}
public static void setLong(String key, long value) {
try {
if(sharedPreferences != null && key != null) {
sharedPreferencesEditor = sharedPreferences.edit();
if (sharedPreferences.contains(key)) sharedPreferencesEditor.remove(key);
sharedPreferencesEditor.putLong(key, value);
sharedPreferencesEditor.apply();
}
}catch (Exception e){e.printStackTrace();}
}
public static long getLong(String key) {
long keyValue = 1;
try {
keyValue = sharedPreferences.getLong(key, 1);
if (keyValue > 0) return keyValue;
else return keyValue;
}catch (Exception e){e.printStackTrace();}
return keyValue;
}
public static void setString(String key, String value) {
try {
if(sharedPreferences != null && key != null) {
sharedPreferencesEditor = sharedPreferences.edit();
if (sharedPreferences.contains(key)) sharedPreferencesEditor.remove(key);
sharedPreferencesEditor.putString(key, value);
sharedPreferencesEditor.apply();
}
}catch (NullPointerException e){e.printStackTrace();}
}
public static String getString(String key) {
String keyValue = "";
try {
if(key != null && sharedPreferences != null) {
keyValue = sharedPreferences.getString(key, "");
if (keyValue.equals(false)) return keyValue;
else {
return keyValue;
}
}
}catch (Exception e){e.printStackTrace();}
return keyValue;
}
public static void setInt(String key, int value) {
try {
if(sharedPreferences != null && key != null) {
sharedPreferencesEditor = sharedPreferences.edit();
if (sharedPreferences.contains(key)) sharedPreferencesEditor.remove(key);
sharedPreferencesEditor.putInt(key, value);
sharedPreferencesEditor.apply();
}
}catch (NullPointerException e){e.printStackTrace();}
}
public static int getInt(String key) {
int keyValue = 0;
try {
if (sharedPreferences.contains(key)) {
keyValue = sharedPreferences.getInt(key, 0);
if (keyValue > 0) return keyValue;
else {
return keyValue;
}
}
}catch (Exception e){
e.printStackTrace();
}
return keyValue;
}
public static void setBoolean(String key, boolean value) {
try {
if(sharedPreferences != null && key != null) {
sharedPreferencesEditor = sharedPreferences.edit();
if (sharedPreferences.contains(key)) sharedPreferencesEditor.remove(key);
sharedPreferencesEditor.putBoolean(key, value);
sharedPreferencesEditor.apply();
}
}catch (Exception e){e.printStackTrace();}
}
public static Boolean getBoolean(String key) {
try {
Boolean keyValue = sharedPreferences.getBoolean(key, false);
if (keyValue.equals(false)) return keyValue;
else {
return keyValue;
}
}catch (Exception e){e.printStackTrace();}
return false;
}
}
AppController
public static final String REMEMBER_ME = "remember_me";
public static final String CUSTOMER_EMAIL_ID = "customer_email_id";
public static final String CUSTOMER_PASSWORD_TEXT = "customers_password_text";
Main Activity
After that, in your main activity create an object of session manager class.
public class MainActivity extends AppCompatActivity {
private Context context;
private SessionManager sessionManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
sessionManager = SessionManager.getInstance(context);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
//NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
}
}
Conclusion
In conclusion, I just want to say create your session manager class carefully. Add all methods of shared preference in the same session manager file. Add this code to your project and enjoy. Thank you.
Write a comment