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