Home > Blockchain >  How to link a ProfileModel to a SharedPreference
How to link a ProfileModel to a SharedPreference

Time:11-12

I have stored data with SharedPreference, I would like to retrieve them now by going through functions

The stored data:

dataUser = getApplicationContext().getSharedPreferences("userData", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = dataUser.edit();
    editor.putString("date", dateString);
    editor.commit();

My ProfileModel:

public class ProfileModel {

    private String date;

    public ProfileModel() {
    }

    public ProfileModel(String date) {
        this.date = date;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

From the ProfileModel, I want to retrieve the value of the putString ("date", ...) with getDate()

So what gives in a text this dateTxt.setText(String.valueOf(model.getDate()));

How I relate the ProfileModel to my stored data ? (Having already done this with Firebase, connect the two data this:

ProfileModel model = snapshot.getValue(ProfileModel.class);

The snapshot this is the name of the DataSnapshot, so I have to find something similar in SharedPreference

CodePudding user response:

implement this library on build.gradle

implementation 'com.google.code.gson:gson:2.8.8'

you can save the entire custom object in shared pref in string by using gson library. To Save any model ->

MyObject myObject = new MyObject;
//set variables of 'myObject', etc.
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

For Getting the object

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Now you can access your obj like all other model class

CodePudding user response:

One way to do it would be putting the SharedPreferences logic in the model constructor:

public ProfileModel(Context context) {
    SharedPreferences prefs = context.getSharedPreferences("userData", Context.MODE_PRIVATE);
    String dateString = prefs.getString("date", <some-default-value>);
    this.date = dateString;
}

This would be an additional constructor along with the 2 you already have.

Then use it like this:

ProfileModel model = new ProfileModel(getApplicationContext());
dateTxt.setText(model.getDate());

This should work, cheers!

  • Related