How do you save/store objects in SharedPreferences on Android?

后端 未结 20 2747
野趣味
野趣味 2020-11-22 13:35

I need to get user objects in many places, which contain many fields. After login, I want to save/store these user objects. How can we implement this kind of scenario?

<
20条回答
  •  面向向阳花
    2020-11-22 14:37

    You can use gson.jar to store class objects into SharedPreferences. You can download this jar from google-gson

    Or add the GSON dependency in your Gradle file:

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

    Creating a shared preference:

    SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);
    

    To save:

    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();
    

    To retrieve:

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

提交回复
热议问题