IRON MAN
IRON MAN

Reputation: 211

check value exists or not using EncryptedSharedPreferences android

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

Upvotes: 0

Views: 730

Answers (1)

darshan
darshan

Reputation: 4579

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"

Upvotes: 0

Related Questions