SharedPreferences In Android

Data storage always makes an issue for developers, especially for beginners, and also when the data is very small. Android provides a very simple solution for small data and for all the primitive types like “String, byte, int” etc. Let us have a look at the code first. In every project of mine I always make a class, mostly with the name of HelperFunctions, and I put the functions to read and to write the data from the shared preferences.

  1. public class HelperFunctions  
  2. {  
  3.     static SharedPreferences preferences;  
  4.   
  5.     //Writes data in shared preference  
  6.     public static void saveInSharedPreferences(Context context, String key, String value) {  
  7.         preferences = PreferenceManager  
  8.             .getDefaultSharedPreferences(context);  
  9.         SharedPreferences.Editor editor = preferences.edit();  
  10.         editor.putString(key, value);  
  11.         editor.apply();  
  12.     }  
  13.   
  14.     //read from SharedPreference  
  15.     public static String readFromSharedPref(Context context, String key) {  
  16.         preferences = PreferenceManager  
  17.             .getDefaultSharedPreferences(context);  
  18.         return preferences.getString(key, null);  
  19.     }  
  20.   
  21. }  
We are done, as whenever you need to store the data that you used most, you can just write.
  1. HelperFunctions.saveInSharedPreferences(context, Constants.PROFILE_ID, mData);  
The data is saved now and similarly you can get it, as shown below.
  1. String userid = HelperFunctions.readFromSharedPref(context, Constants. PROFILE_ID);  
Note

In place of the constants, you can write your String “PreferenceName”.

Let’s have a look at the advantages.

 

  • In small enterprise apps, you can save the user login credentials to use them in future or to send the data on the server with the user Id etc.
  • If you have to update the application at the specific time, in the first install of your Application, you can check for Boolean stored SharedPreferences.
  • Even if you want to pass JSON between the activities, you can easily do this even if you are a beginner.
    The code given above is tested and works fine, when you can copy the code. If you find any improvements, share and help others to write better code.
Ebook Download
View all
Learn
View all