check value exists or not using EncryptedSharedPreferences android

旧街凉风 提交于 2021-01-29 15:26:20

问题


I use the EncryptedSharedPreferences to store value while login...i want to change text in navigation drawer of home activity

so when user is loggedin it will show logout else it will show login navigation drawer

Loginactivity:--------

 sharedPreferences = EncryptedSharedPreferences.create(
        "secret_shared_prefs",
        masterKeyAlias,
        baseContext,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    ) as EncryptedSharedPreferences

while login im doing this

  val editor = sharedPreferences.edit()
   editor.putString("EmailId", edtEmailId)
   editor.putString("password", edtPassword)
     editor.apply()

checking in Homeactivity:---------

        val menu: Menu = bind.navRightView.getMenu()

    val nav_connection: MenuItem = menu.findItem(R.id.nav_login)

   val sharedPreference =
            applicationContext.getSharedPreferences("secret_shared_prefs", Context.MODE_PRIVATE)
    val value: String = sharedPreference.getString("EmailId", null).toString()

    if(!sharedPreference.contains(value))
    {
        nav_connection.title = "Loginn"

    }
    else{
        nav_connection.title = "Logout"

    }

well output of this code is always having a title as loginn that means it detecting value as null need help for EncryptedSharedPreferences thanks


回答1:


You are adding the values but not saving them to SharedPreferences.
You should be using commit() or apply().

Do this:

   val editor = sharedPreferences.edit()
   editor.putString("EmailId", edtEmailId)
   editor.putString("password", edtPassword)
   editor.apply() // Important

I also see that you are calling

val sharedPreference = applicationContext.getSharedPreferences("secret_shared_prefs", Context.MODE_PRIVATE)`

which gives you the normal SharedPreference, I guess.
You should be using:

val sharedPreferences = EncryptedSharedPreferences.create(
        "secret_shared_prefs",
        masterKeyAlias,
        baseContext,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    ) as EncryptedSharedPreferences


Then check if the email address is empty or not.

if(!sharedPreference.contains("EmailId") 
    nav_connection.title = "Loginn"
else 
    nav_connection.title = "Logout"


来源:https://stackoverflow.com/questions/65436252/check-value-exists-or-not-using-encryptedsharedpreferences-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!