Search code examples
androidkotlinsharedpreferences

How to save data object in sharedpreference from retrofit2. More information inside


I have data class:

@Parcelize
data class CurrentUser(
    @SerializedName("id")
    val id: String,
    @SerializedName("name")
    val firstName: String,
    @SerializedName("surname")
    val lastName: String,
    @SerializedName("avatarPath")
    val avatarPath: String,
    @SerializedName("manager")
    val manager: ResourceManager,
    @SerializedName("department")
    val department: Departments,
    @SerializedName("role")
    val role: Role,
    @SerializedName("email")
    val email: String,
    @SerializedName("status")
    val status: String,
    @SerializedName("country")
    val country: Countries,
    @SerializedName("city")
    val city: Cities,
    @SerializedName("activities")
    val activities: List<String>
) : Parcelable

I'm use POST query (with retrofit 2) and get information about current user:

@GET("url")
    suspend fun getCurrentUser(
        @HeaderMap headers: Map<String, String>
    ) : Response<CurrentUser, Error>

And I want to save this current user into shared shared preferences and then restore this current user in several fragments

Now it working, but I get user information in ViewModel, but I want to do it in SharedPreference

Thank you


Solution

  • You should convert it in JSON and store it as a String :

    class SharedPreferenceManager(val context: Context) {
    
        private val PREFS_NAME = "sharedpref"
        val sharedPref: SharedPreferences =
            context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    
        fun saveUSer(user: CurrentUser) {
            sharedPref.edit().putString("user", Gson().toJson(user)).apply()
        }
    
        fun getUser(): CurrentUser? {
            val data = sharedPref.getString("user", null)
            if (data == null) {
                return null
            }
            return Gson().fromJson(data, CurrentUser::class.java)
        }
    
    }