I know this is a well-known question (for example: How do you save/store objects in SharedPreferences on Android?) , but I was wondering if it was better to store an object in shared preferences (using json) or as a static object of an activity (companion object). This is an object that I will use it in almost all the activities and fragments.
For example, I have an User object.
The first solution will look like this:
val mUser = User(x,x,x...)
val mUserJson = Gson().toJson(mUser)
mSharedPreferences
.edit()
.putString(USER_DATA, mUserJson)
.apply()
And for the second one, I declared the object on the first activity, and then on another activity I initialized it.
class FirstActivity : AppCompatActivity() {
companion object {
lateinit var mUser: User
}
}
On another activity:
FirstActivity.mUser = User(x,x,x...)
I don't know if there is a problem with the second solution (efficiency?) but as for the first solution I have to initialized shared preferences for each activity that I'm willing to use the User object (is this too bad?). Also, if I want to change a User variable, I have to reconvert the user object into json and rewrite this preference:
val mUserPref = mSharedPreferences.getString(USER_DATA, "")
.run { Gson().fromJson(this, User::class.java) }
mUserPref.variable = new_value
mSharedPreferences
.edit()
.putString(USER_DATA, Gson().toJson(mUserPref))
.apply()
So, can someone explain me which is the best solution and why? Thank you :)