2013-10-13 28 views
2

我想检查一个字符串值,但如果它总是输入else, 这里有什么错误?谢谢无法检查字符串值

public void alertBtn(View v){ 
    EditText text = (EditText)findViewById(R.id.editText1); 
    String value = text.getText().toString(); 
    String password="asd"; 
    if (value==password){ 

      new AlertDialog.Builder(this) 
      .setTitle("Success") 
      .setMessage("Correct Password") 
      .setNeutralButton("OK", null) 
      .show(); 
     } 
    else 
     new AlertDialog.Builder(this) 
     .setTitle("Error") 
     .setMessage("Wrong password") 
     .setNeutralButton("OK", null) 
     .show(); 



} 
+0

请不要使用==来比较字符串。请不要。 – Maroun

+0

使用equals()函数 –

+0

对于那些回答,您可能还想给出一个解释.....特别是当这个问题已被回答1000次。 – Maroun

回答

1

使用.equals.equalsIgnoreCase()比较字符串

What is the difference between == vs equals() in Java?

if (value.equals(password)){ 

而且EDITTEXT的初始化移动到onCreate。有没有需要初始化按钮的EditText每次点击

text = (EditText)findViewById(R.id.editText1); // in onCreate 

,并宣布EditText text为类成员

+0

非常感谢,有没有可以找到基本命令的地方? –

1

使用等于()函数

尝试

if(value.equals(password)) { 

} 
2

使用==运算符将比较字符串的引用而不是字符串本身。

String value = text.getText().toString(); 
String password="asd"; 

if (value.equals(password)) 
{ 
} 
0

here

使用String.equals(String other)功能比较字符串,而不是==操作。

函数检查字符串的实际内容,==运算符检查对象的引用是否相等。请注意,字符串常量通常是“interned”的,这样两个具有相同值的常量实际上可以与==进行比较,但最好不要依赖它。