• Latest Code...

    Featured Post

    Implementing Hilt in a Kotlin Android Jetpack Compose Project with MVVM Architecture

     In modern Android development, maintaining a scalable codebase can be challenging, especially when it comes to dependency management. Hilt,...

    How to save, retrieve and remove in android using SharedPreferences

    Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. Objects that are returned from the various get methods must be treated as immutable by the application.

    Save on SharedPreferences

     // Saving Data on Shared preference for offline storage, here store json string in private mode, ie accessiable to only this application  
          public void saveDataOnSharedPreference(Context applicationContext,String JsonSting) {  
               // TODO Auto-generated method stub  
               SharedPreferences settings;  
               Editor editor;  
               settings = applicationContext.getSharedPreferences("JSONPREFERENCES", Context.MODE_PRIVATE); // 1  
               editor = settings.edit(); // 2  
               editor.putString(JSONPPREFSTOREKEY, JsonSting); // 3  
               editor.commit(); // 4  
          }  
    


    Retrieve on SharedPreferences

     // Getting saved data on sharedpreference in android  
          public String getDataFromSharedPreference(Context context) {  
               SharedPreferences settings;  
               String jsonString;  
               settings = context.getSharedPreferences(JSONPREFERENCES, Context.MODE_PRIVATE); // 1  
               jsonString = settings.getString("JSONPREFERENCES", null); // 2  
               return jsonString;  
          }  
    

    Remove on SharedPreferences



          // remove or clear json data from the shared preference, when internet connection is aviable  
          public void removeDataFromSharedPreference(Context applicationContext) {  
               SharedPreferences settings;  
               Editor editor;  
               settings = applicationContext.getSharedPreferences("JSONPREFERENCES", Context.MODE_PRIVATE); // 1  
               editor = settings.edit(); // 2  
               editor.remove("JSONPPREFSTOREKEY"); // 3  
               editor.commit(); // 4  
          }  
    


    Happy Coding !!!

    Contact Form

    Name

    Email *

    Message *