简体   繁体   中英

Android EditText Value Error?

I'm testing out some stuff on android as a beginner and was trying to grab value entered in a EditText when a button was clicked , then compare it to a string value that I defined inside the class, then use if (EditText == stringDefined) else () , but my code always jumps on the else part even if the correct text is entered, any help is appreciated. Here is the code :

Button mButton;
EditText mEdit1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    final String user = "admin";

    mButton = (Button)findViewById(R.id.BTN_login);
    mEdit1   = (EditText)findViewById(R.id.editText1);


    mButton.setOnClickListener(
            new View.OnClickListener()
            {
                public void onClick(View view)
                {
                    String userEntered = mEdit1.getText().toString().trim();

                    Intent intent = new Intent(Login.this, Success.class);
                    if(userEntered == user){
                        startActivity(intent);
                    }

                    else{
                        AlertDialog.Builder errAlert = new AlertDialog.Builder(Login.this);
                        errAlert.setTitle("Wrong Credentials");
                        errAlert.setMessage("Wrong username");
                        errAlert.setCancelable(true);
                        errAlert.show();
                    }
                }
            });
}

Use equals method :

if(userEntered.equals(user)){
    startActivity(intent);
}

==用于比较原始类型,而java.lang.String类的equals()方法比较内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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