简体   繁体   English

Android字符串比较

[英]Android string comparison

I am trying to compare two EditTexts when the user clicks a button. 我试图在用户单击按钮时比较两个EditText。 However the IF statement returns true even if the two strings are different. 但是,即使两个字符串不同,IF语句也会返回true。

    final EditText email= (EditText)findViewById(R.id.txtEmail);
    final EditText emailconf= (EditText)findViewById(R.id.txtEmailConf);
    final EditText password = (EditText)findViewById(R.id.txtPassword1);
    final EditText passconf = (EditText)findViewById(R.id.txtPasswordConf);

    final String emailInput = email.getText().toString();
    final String emailconfInput = emailconf.getText().toString();
    final String passinput = password.getText().toString();
    final String passconfinput = passconf.getText().toString();

    //When our register button is pressed
 btnRegister.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(emailInput.equalsIgnoreCase(emailconfInput)){
                if(passinput.equalsIgnoreCase(passconfinput)){
                    new RegisterTask().execute();
                }
                else{
                    displayDialogue("Error", "Your password's do not match, please try again", "Re-input details");

                }

            }else{
                displayDialogue("Error", "Your email's do not match, please try again", "Re-input details");

            }


        }

    });

If the two are correct then it will run an Asynctask (RegisterTask) 如果两者正确,则它将运行Asynctask(RegisterTask)

Any help would be great, thanks 任何帮助都很好,谢谢

final String passinput = password.getText().toString();
final String passconfinput = passconf.getText().toString();

Move this part to the onClick() so that the text is pulled from the EditText s only then. 将此部分移到onClick()以便仅从EditText文本。 In onCreate() they're both empty and two empty strings will match. onCreate()它们都是空的,两个空字符串将匹配。

Are you sure it is giving true in every case? 您确定在每种情况下它都是正确的吗? Apart from equals method try compareTo method it will work fine 除了equals方法之外,尝试compareTo方法也可以

I recommend to you Sanitise both fields, because if the user puts an empty space at the beginning or end of the field, equalsIgnoreCase will return false. 我建议您对两个字段都进行清理,因为如果用户在字段的开头或结尾放置一个空格, equalsIgnoreCase将返回false。

Try methods like trim() , remove invalid chars, and then compare, it's up to what you want to check. 尝试使用trim()类的方法,删除无效的字符,然后进行比较,这取决于您要检查的内容。

if(emailInput == emailconfInput){

如果您更改为不应该有问题...哦,我也不建议忽略密码检查的大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM