Search code examples
javaandroidsharedpreferences

Save Model class object in SharedPreferences


I am new to android development. I am saving user profile information in shared preferences so that whenever I am required to show the user name, email or other data I call it from shared preferences instead of calling from the database again and again. I want to save and get a complete profile instead of getting a single string. Below are functions I use

public void save(String key, String value) {
    SharedPreferences.Editor editor
        = context.getSharedPreferences("data", context.MODE_PRIVATE).edit();
    editor.putString(key, value);
    editor.commit();
}

public String get(String key) {
    SharedPreferences sharedPreferences
        = context.getSharedPreferences("data", context.MODE_PRIVATE);
    return sharedPreferences.getString(key, "");
}

The function I want is something like below

public void save(String key, MyModel object) {
    SharedPreferences.Editor editor
        = context.getSharedPreferences("data", context.MODE_PRIVATE).edit();
    editor.putString(key, object);
    editor.commit();
}

But shared preferences take the only string to save and get. Is there any possible solution to save objects in it? Or any alternative to shared preferences. (excluding SQLite or another complex database)


Solution

  • this one to save data

    public void saveData(String key, MyModel object) {
        save(key, new Gson().toJson(object));
    }
    

    this one to get data

    public MyModel getData(String key) {
        String data = get(key);
        return new Gson().fromJson(data, MyModel.class);
    }
    

    How it works?

    This save method converts your model object into a JSON string and then the string is saved into shared preferences and the same in get function. It gets data in the form of JSON string and then it converts it to your object and returns a value. For save and get use your own functions