首页 > 解决方案 > 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()
    }
}

标签: androidandroid-studiokotlin

解决方案


Maybe try this:

applicationContext.getSharedPreferences("CGEEnergy", 0).edit().clear().commit()

推荐阅读