我有資料類:
@Parcelize
data class CurrentUser(
@SerializedName("id")/span>(
val id: 字串。
@SerializedName("name"/span>)
val firstName: 字串。
@SerializedName("surname")
val lastName: 字串。
@SerializedName("avatarPath")
val avatarPath: 字串。
@SerializedName("Manager")
val manager。資源管理員。
@SerializedName("department")
val department: 部門。
@SerializedName("role")
val role: 角色。
@SerializedName("email")
val email。字串。
@SerializedName("status")
val status。字串。
@SerializedName("country")
val country: 國家。
@SerializedName("city")
val city: 城市。
@SerializedName("活動")
val activities: List<String>
) : 可包裹的
我使用POST查詢(使用retrofit 2),并獲得當前用戶的資訊:
我使用POST查詢(使用retrofit 2)。
@GET("url"/span>)
suspend fun getCurrentUser (
@HeaderMap headers: Map<String, String>
) : Response<CurrentUser, Error>
而且我想把這個當前用戶保存到共享共用的偏好中,然后在幾個片段中恢復這個當前用戶
現在它在作業,但我在ViewModel中得到了用戶資訊,但我想在SharedPreference中做到這一點。謝謝你
uj5u.com熱心網友回復:
你應該把它轉換為JSON格式并存盤為一個字串。
class SharedPreferenceManager(val context: Context) {
private val PREFS_NAME = "sharedpref"
val sharedPref: SharedPreferences =
背景關系.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"/span>, null)
if (data == null) {
return null {
}
return Gson().fromJson(data, CurrentUser::class.java)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/311876.html
標籤:
上一篇:如何在Java中通過Intent呼叫一個Kotlin格式的類?
下一篇:保存密碼常量的最佳方法
