【问题标题】:String Comparison error in a android code [duplicate]android代码中的字符串比较错误[重复]
【发布时间】:2015-11-22 18:26:53
【问题描述】:

我正在使用 Sqlite 数据库保存和检索的简单代码。我的问题是我的代码总是使用 else 部分,即使字符串相同。 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 和调试模式检查了输出。 utext 的值等于str,ptext 的值等于str1。我在这里犯了什么错误吗?我什么也没找到。

http://postimg.org/image/huvmxhgup/

public void onClick(View v) {
            utext=t1.getText().toString();
            ptext=t2.getText().toString();

            Cursor c = db.rawQuery("SELECT * FROM " + tbl_name+" WHERE USERNAME= '"+utext+"' AND PASSWORD= '"+ptext+"'", null);
              if(c.moveToLast() ) {
                      str=c.getString(c.getColumnIndex("USERNAME"));
                      str1=c.getString(c.getColumnIndex("PASSWORD"));
                      Toast.makeText(getApplicationContext(), "True : "+str+", "+str1, Toast.LENGTH_LONG).show();
              }
              else
                  Toast.makeText(getApplicationContext(), "FALSE", Toast.LENGTH_LONG).show();
              if(str==utext || str1==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();

        }

【问题讨论】:

    标签: android string sqlite logic


    【解决方案1】:

    在 java 中,== 比较对象引用而不是内容。

    == 检查两个字符串是否是同一个对象,而 .equals().compareTo() 检查两个字符串是否有 相同的值。

    您可以在java中使用.equals().compareTo()方法来比较字符串

    因此,替换

    if(str==utext || str1==ptext)
    

    if(str.equals(utext) || str1.equals(ptext))
    

    if(str.compareTo(utext)==0 || str1.compareTo(ptext)==0)
    

    【讨论】:

      【解决方案2】:

      您应该始终使用.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();
      

      【讨论】:

        猜你喜欢
        • 2013-04-15
        • 1970-01-01
        • 1970-01-01
        • 2012-09-26
        • 1970-01-01
        • 2014-11-28
        • 1970-01-01
        • 2012-01-11
        相关资源
        最近更新 更多