Shared Preferences in Android

Overview

Shared Preference is a way to store and receive primitive data in the form of key-value pair.

Steps to follow

  • Create an instance of Shared Preference
 SharedPreferences sharedPreference = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreference.edit();

  • Add the data in the form of Key/Value pair in the Editor
 editor.putInt("key", value);
editor.apply();
  • To get the data from Shared Preference
 SharedPreferences sharedPreference = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
sharedPreference.getInt("key", defaultValue);
  • To clear data from Shared Preference
 SharedPreferences sharedPreference = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreference.edit();
editor.clear();
editor.apply();
  • Hello World

Do's and Dont's

  • If you are creating a Shared Preference, create a separate class for it and provide the object with the help of a synchronized method.
 public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
  • Hello World!!!

Reference




Comments

Popular posts from this blog

Architecture Components in Android

DataBinding in Android

SSLSocketFactory in Android