【问题标题】:check value exists or not using EncryptedSharedPreferences android检查值是否存在使用 EncryptedSharedPreferences android
【发布时间】:2021-04-02 18:48:13
【问题描述】:

我在登录时使用 EncryptedSharedPreferences 来存储值...我想更改主页活动导航抽屉中的文本

所以当用户登录时它将显示logout 否则它将显示login 导航抽屉

登录活动:--------

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

登录时我正在这样做

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

检查 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"

    }

这段代码的输出总是有一个标题为 loginn,这意味着它检测到的值为 null 需要有关 EncryptedSharedPreferences 的帮助,谢谢

【问题讨论】:

标签: android kotlin sharedpreferences logout encrypted-shared-preference


【解决方案1】:

您正在添加值,但没有将它们保存到 SharedPreferences
您应该使用commit()apply()

这样做:

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

我也看到你在打电话

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

我猜这会给你正常的SharedPreference
您应该使用:

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


然后检查邮箱地址是否为空。

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

【讨论】:

  • 嗨,对不起,我忘了添加这个问题,但我已经应用了,但没有工作
  • 需要帮助,因为上面的代码也不能与 editor.apply() 一起使用
  • 但是我已经完成了 loginactivity ...但是需要检查 homeactivity
  • 在 HomeActivity 中初始化变量sharedPreference 并使用getString()
  • 有什么解决办法吗??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2012-03-10
  • 1970-01-01
  • 2016-07-06
  • 2021-02-10
  • 1970-01-01
  • 2012-01-19
相关资源
最近更新 更多