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)

并尊重CCD_ 2方法的CCD_

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。如果要确保密钥是否存在,则需要对密钥调用contains

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

相关内容

  • 没有找到相关文章

最新更新