android - Android Studio 注销:清除保存的首选项 kotlin
问题描述
我有一个带有登录按钮的主要活动,当用户登录时我保留一个令牌(保存的首选项)。如果用户已登录,应用程序会直接进入我的第二个活动,即 SearchActivity。我在那里添加了一个注销按钮,但我似乎无法让它工作。我希望它释放保存的令牌。我是 Kotlin 和 Android 的新手,所以任何帮助都会非常有用。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
login_button.setOnClickListener {
buttonClicked()
}
if (getTokenFromPrefs()?.length!! > 0) {
openSearchActivity()
}
}
private fun buttonClicked() {
val username = username_edittext.text.toString()
val password = password_edittext.text.toString()
val call = RequestManager.service.login(username, password)
call.enqueue(object : Callback<List<LoginResponse>> {
override fun onResponse(
call: Call<List<LoginResponse>>,
response: Response<List<LoginResponse>>
) {
loader.visibility = View.GONE
if (response.isSuccessful) {
openSearchActivity()
saveTokenToPrefs("token")
} else {
}
}
override fun onFailure(call: Call<List<LoginResponse>>, t: Throwable) {
loader.visibility = View.GONE
}
})
}
val TOKENPREFSKEY = "tokenprefskey"
private fun saveTokenToPrefs(token: String) {
val pref = applicationContext.getSharedPreferences("CGEEnergy", 0)
val editor = pref.edit()
editor.putString(TOKENPREFSKEY, token)
editor.commit()
}
private fun getTokenFromPrefs(): String? {
val pref = applicationContext.getSharedPreferences("CGEEnergy", 0)
return pref.getString(TOKENPREFSKEY, "")
}
private fun openSearchActivity() {
val intent = Intent(this, SearchActivity::class.java)
startActivity(intent)
finish()
}
我的搜索活动类是这样的(现在有点空):
class SearchActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
}
override fun onResume() {
super.onResume()
}
}
解决方案
Maybe try this:
applicationContext.getSharedPreferences("CGEEnergy", 0).edit().clear().commit()
推荐阅读
- python - Dash-plotly 部署为 android 或 IOS 的 apk
- django-forms - 带有自定义表单的 Django UserCreationForm 不起作用
- php - 检查函数是否属于命名空间或全局
- r - 如何使用 geom_bar() 在 R 中创建两个分组列
- php - 创建一个以 CollectionType 为父的自定义字段类型
- r - RStudio,更新包,重新启动 R,RStudio 进入无限循环
- amazon-web-services - s3fs 获取文件抛出输入/输出错误或无法从远程文件“/mnt/s3/”读取:失败
- r - 在 r 中使用 ggplot2 创建散点图,其中包含所有点但点的 1 条回归线通过分组变量进行区分
- terraform-provider-azure - 在创建资源之前创建服务原则
- linq - 无法使用 MVC 核心中的影子属性翻译 LINQ 表达式