如何将Retrofit2返回的用户数据对象存储到SharedPreferences中
前置依赖
我们需要用Gson实现对象和JSON字符串的互转,先在模块级build.gradle中添加依赖(已集成可跳过):
dependencies { implementation 'com.google.code.gson:gson:2.10.1' // 如果需要加密存储,添加EncryptedSharedPreferences依赖 implementation "androidx.security:security-crypto:1.1.0-alpha06" }
1. 封装SharedPreferences操作工具类
直接写单例工具类,避免重复创建实例,使用ApplicationContext防止内存泄漏:
import android.content.Context import com.google.gson.Gson object UserSpHelper { private const val SP_NAME = "user_info_sp" private const val KEY_CURRENT_USER = "current_user" // 懒加载获取SharedPreferences实例 private val sp by lazy { App.context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE) } private val gson = Gson() // 保存用户信息 fun saveCurrentUser(user: CurrentUser) { sp.edit() .putString(KEY_CURRENT_USER, gson.toJson(user)) .apply() } // 读取用户信息 fun getCurrentUser(): CurrentUser? { val userJson = sp.getString(KEY_CURRENT_USER, null) ?: return null return runCatching { gson.fromJson(userJson, CurrentUser::class.java) }.getOrNull() } // 退出登录时清空用户信息 fun clearUserInfo() { sp.edit() .remove(KEY_CURRENT_USER) .apply() } }
注意:上面的
App.context是全局ApplicationContext的获取入口,你需要在自定义Application类中初始化:class App : Application() { companion object { lateinit var context: Context private set } override fun onCreate() { super.onCreate() context = this } }同时记得在AndroidManifest.xml的application节点配置
android:name=".App"
2. 接口请求成功后存储用户信息
在你ViewModel的请求逻辑中,拿到接口返回的CurrentUser实例后,直接调用保存方法即可:
viewModelScope.launch { val response = apiService.getCurrentUser(headers) if (response.isSuccessful) { response.body()?.let { user -> // 存储用户信息到SP UserSpHelper.saveCurrentUser(user) // 其他业务逻辑 } } }
3. Fragment中读取用户信息
任意需要用到用户信息的地方,直接调用读取方法即可:
// 在Fragment中使用示例 val currentUser = UserSpHelper.getCurrentUser() currentUser?.let { user -> // 读取用户字段做业务逻辑,比如显示用户名 binding.tvUserName.text = "${user.firstName} ${user.lastName}" } ?: run { // 用户信息为空,跳转登录等逻辑 }
注意事项
- CurrentUser内部嵌套的
ResourceManager、Departments、Role等自定义类,需要是可序列化的data class,保证Gson可以正常解析 - 如果需要存储敏感信息,不要用普通SharedPreferences,替换为Jetpack的EncryptedSharedPreferences加密存储,避免信息泄露
- 开启混淆的情况下,需要在混淆规则中添加CurrentUser及所有嵌套类的混淆豁免规则,防止序列化失败
内容的提问来源于stack exchange,提问作者Viacheslav Khailenko
相关产品推荐
相关产品推荐

