SharedPreferences 检查数据是否已经存在

SharedPreferences check if data already exist

我这里有一个问题,如果相同的数据或值已经存在于 sharedpreferences 中,如果该数据已经存在,它会显示 toast,所以我必须输入其他值。我尝试用 contains 检查它,但每次我输入相同的值时,它都会不断替换相同的值

这是代码

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
    }

}

你应该检查键是否存在,而不是值

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

并且也尊重 dataExist 方法的 return

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

编辑 - 工作示例

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

您当前正在 value 上调用 contains。如果要确认key是否存在,需要在key上调用contains

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