Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Saving objects into SharedPreferences

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 132
    Comment on it

    To Save Object values into SharedPreferences, you can use GSON library.

     

    To save objects follow these steps:

     

    Add Gson library dependency in your Gradle (App Level):

    dependencies {
    
        compile 'com.google.code.gson:gson:2.4'
    
    }
    

    Use the latest version of Gson library, currently the latest version is 2.4.

    Suppose this is the class of which object you want to save:

     

    public class ExampleClass {
    
        public String name;
        public int id;
        public ArrayList<String> list = new ArrayList<>();
        ...
        ...
        ...
    }
    

    To save object use this code:

     

    ExampleClass myObject = new ExampleClass();
    
    Gson gson = new Gson();
    String json = gson.toJson(myObject);
    
    SharedPreferences sharedPref = context.getSharedPreferences("pref1", 0);
    SharedPreferences.Editor accessTokenEditor = sharedPref.edit();
    accessTokenEditor.putString("my_object", json);
    accessTokenEditor.commit();

     

    To retrieve object use this code:

    Gson gson = new Gson();
    SharedPreferences sharedPref = con.getSharedPreferences("pref1",0);
    
    ExampleClass myObject = gson.fromJson(sharedPref.getString("my_object", ""), ExampleClass.class);

    And finally if you want to clear the saved object from SharedPreferences, use this code:

    SharedPreferences sharedPref = con.getSharedPreferences("pref1", 0);
    SharedPreferences.Editor accessTokenEditor = sharedPref.edit();
    accessTokenEditor.clear();
    accessTokenEditor.apply();

    Hope it helps! . Reply in the comments if you have any query.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: