Home > other >  SharedPreferences check if data already exist
SharedPreferences check if data already exist

Time:04-05

i have a problem here, i want to make if same data or value already exists in sharedpreferences it show toast if this data already exist, so i must input other value. i try to check it with contains but everytime i type same value it keeps replacing the same value

this is the code

binding.btnContinue.setOnClickListener  {
        dataExist()
        saveData()
    }
}

private fun saveData() {
    val pref = this.getSharedPreferences(Data.Preferences.PREF_NAME, MODE_PRIVATE)

    val fullName = binding.etFullName.text.toString()
    val jobPref = binding.etJob.text.toString()
    val emailPref = binding.etEmailSignUp.text.toString()
    val passPref = binding.etPassSignUp.text.toString()

    pref.edit {
        putString(Data.Preferences.PREF_FULLNAME, fullName)
        putString(Data.Preferences.PREF_JOB, jobPref)
        putString(Data.Preferences.PREF_EMAIL, emailPref)
        putString(Data.Preferences.PREF_PASS, passPref)
        apply()
    }

    val intent = Intent(this, SignInActivity::class.java)
    startActivity(intent)
}

private fun dataExist(): Boolean {
    val pref = this.getSharedPreferences(Data.Preferences.PREF_NAME, MODE_PRIVATE)

    val checkName = pref.getString(Data.Preferences.PREF_NAME, "")
    val checkJob = pref.getString(Data.Preferences.PREF_JOB, "")

    if (pref.contains(checkName)){
        Toast.makeText(this, "Name already exist", Toast.LENGTH_SHORT).show()
        return true
    }else{
        return false
    }

}

CodePudding user response:

you should check key existence, not value

boolean hasKey = pref.contains(Data.Preferences.PREF_NAME)

and also respect return of dataExist method

if (!dataExist()) saveData() // save only when not exists

edit - working example

if (pref.contains(Data.Preferences.PREF_NAME)){
    val checkName = pref.getString(Data.Preferences.PREF_NAME, null)
    val fullName = binding.etFullName.text.toString()
    // returns true when key exists and value stored under this key
    // is exactly same as entered in EditText
    if (fullName.equals(checkName)) return true
}
return false // no key at all, so no data stored

CodePudding user response:

You are currently calling contains on the value. You need to call contains on the key if you want to ensure whether the key exists or not.

  if (pref.contains(Data.Preferences.PREF_NAME)){
        Toast.makeText(this, "Name already exist", Toast.LENGTH_SHORT).show()
        return true
    }else{
        return false
    }
  • Related