android代码中的字符串比较错误
我正在使用Sqlite数据库保存和检索的简单代码。我的问题是,即使字符串相同,我的代码也总是使用else部分。android代码中的字符串比较错误,android,string,sqlite,logic,Android,String,Sqlite,Logic,我正在使用Sqlite数据库保存和检索的简单代码。我的问题是,即使字符串相同,我的代码也总是使用else部分。 Toast.makeText(getApplicationContext(),“No UName:”+utext+,“+str+”;Pswd:“+ptext+”,“+str1,Toast.LENGTH_LONG).show() 而不是, Toast.makeText(getApplicationContext(),“Yes UName:”+utext+,“+str+”;Pswd:“+p
Toast.makeText(getApplicationContext(),“No UName:”+utext+,“+str+”;Pswd:“+ptext+”,“+str1,Toast.LENGTH_LONG).show()代码>
而不是,
Toast.makeText(getApplicationContext(),“Yes UName:”+utext+,“+str+”;Pswd:“+ptext+”,“+str1,Toast.LENGTH_LONG).show()代码>
我用toast和debug模式检查了输出。utext的值等于str,ptext的值等于str1。这里有什么我弄错的吗?我什么也没找到
在java中,=
比较对象引用而不是内容。
==
检查两个字符串是否为同一对象,而
.equals()
或.compareTo()
检查两个字符串是否具有相同的值
相同的值
您可以使用java中的方法.equals()
或.compareTo()
来比较字符串
因此,替换
if(str==utext || str1==ptext)
与
或
您应该始终使用.equals()
进行字符串比较。把你的代码改成这个
if(str.equals(utext) || str1.equals(ptext))
Toast.makeText(getApplicationContext(), "Yes UName: "+utext+","+str+"; Pswd: "+ptext+","+str1, Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "No UName: "+utext+","+str+"; Pswd: "+ptext+","+str1, Toast.LENGTH_LONG).show();
if(str.equals(utext) || str1.equals(ptext))
if(str.compareTo(utext)==0 || str1.compareTo(ptext)==0)
if(str.equals(utext) || str1.equals(ptext))
Toast.makeText(getApplicationContext(), "Yes UName: "+utext+","+str+"; Pswd: "+ptext+","+str1, Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "No UName: "+utext+","+str+"; Pswd: "+ptext+","+str1, Toast.LENGTH_LONG).show();