Home > front end >  How to remove values from Shared
How to remove values from Shared

Time:11-17

I am working on android using kotlin, I have saved userId in shared preferences but when I try to remove it, it didn't removed. Am I doing it right?

override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId

        if (id == R.id.action_settings) {
            val pref = applicationContext.getSharedPreferences("Auth", Context.MODE_PRIVATE)
            
            val editor: SharedPreferences.Editor = pref.edit()
            editor.remove("UserId")
            editor.commit()
  
            Toast.makeText(this, "Sign out",  Toast.LENGTH_SHORT).show()
        }
        return super.onOptionsItemSelected(item)
    }

Login code, this is my fun which I am calling when user login and it is called like this:

saveUserIdSession(mAuth.currentUser.uid.toString())
fun saveUserIdSession(id: String) {
        val sharedPreferences: SharedPreferences? =
            this.activity?.getSharedPreferences("Auth", Context.MODE_PRIVATE)
        var editor: SharedPreferences.Editor = sharedPreferences!!.edit()
        editor.apply{
            putString("UserId", id)
        }.apply()
    }

CodePudding user response:

Deleting Android Shared Preferences in one line :-)

context.getSharedPreferences("Auth", 0).edit().clear().commit();

Thanks, Programiner

Note:- Upvote Answer if Helpful.

  • Related