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

后端 未结 20 2466
野趣味
野趣味 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:33

    I had trouble using the accepted answer to access Shared Preference data across activities. In these steps, you give getSharedPreferences a name to access it.

    Add the following dependency in the build.gradel (Module: app) file under Gradle Scripts:

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

    To Save:

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

    To Retrieve in a Different Activity:

    SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);
    
    Gson gson = new Gson();
    String json = mPrefs.getString("Key", "");
    MyObject obj = gson.fromJson(json, MyObject.class);
    

提交回复
热议问题