Android studio logout: clear saved preferences kotlin

C-Bk :

I have one main activity with a login button, and I keep a token when a user logs in (saved preferences). If the user is logged in, the app goes straight to my second activity, which is SearchActivity. I have added a logout button there, but I cant seem to make it work. I want it to release the saved token. I'm new to Kotlin and Android, so any help would be really useful.

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()
    }

My search activity class is this (kind of empty for now):

class SearchActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)


    }

    override fun onResume() {
        super.onResume()
    }
}
Littlish :

Maybe try this:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7234&siteId=1