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.
- public class HelperFunctions
- {
- static SharedPreferences preferences;
-
-
- public static void saveInSharedPreferences(Context context, String key, String value) {
- preferences = PreferenceManager
- .getDefaultSharedPreferences(context);
- SharedPreferences.Editor editor = preferences.edit();
- editor.putString(key, value);
- editor.apply();
- }
-
-
- public static String readFromSharedPref(Context context, String key) {
- preferences = PreferenceManager
- .getDefaultSharedPreferences(context);
- return preferences.getString(key, null);
- }
-
- }
We are done, as whenever you need to store the data that you used most, you can just write.
- HelperFunctions.saveInSharedPreferences(context, Constants.PROFILE_ID, mData);
The data is saved now and similarly you can get it, as shown below.
- 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.