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. //Writes data in shared preference
  5. public static void saveInSharedPreferences(Context context, String key, String value) {
  6. preferences = PreferenceManager
  7. .getDefaultSharedPreferences(context);
  8. SharedPreferences.Editor editor = preferences.edit();
  9. editor.putString(key, value);
  10. editor.apply();
  11. }
  12. //read from SharedPreference
  13. public static String readFromSharedPref(Context context, String key) {
  14. preferences = PreferenceManager
  15. .getDefaultSharedPreferences(context);
  16. return preferences.getString(key, null);
  17. }
  18. }
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.