开发者

Comparing text from EditText with string from database

开发者 https://www.devze.com 2023-03-03 04:20 出处:网络
This code should compare text entered into R.id.editUserName with R.stri开发者_StackOverflowng.DB_username and, if they match, log you in, else show a toast that they don\'t match.

This code should compare text entered into R.id.editUserName with R.stri开发者_StackOverflowng.DB_username and, if they match, log you in, else show a toast that they don't match.

public void signIn(View view) {

  EditText editUserName = (EditText)findViewById(R.id.editUserName);
  String userName = editUserName.getText().toString();

  if ( userName ==  getResources().getString(R.string.DB_username)) {
    // log in
    setContentView(R.layout.screen1);
  } else {
    // show toast
    Toast toast = Toast.makeText(getApplicationContext(), userName+" != "+getResources().getString(R.string.DB_username), Toast.LENGTH_LONG);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();
  }
}

Even when they do match, it still shows a toast, such as "Roger != Roger"... how could that be?


Dont compare them like that. Use the string comparison function provided by java to compare them.

Refer here: http://www.devdaily.com/java/edu/qanda/pjqa00001.shtml


You can't compare strings like that in Java. You need:

if (userName.equals(...))

What your code is saying is "are these two things the exact same object in memory?" rather than "is the content of each of these objects the same?"


I think you need to look up Java equality. == is reference equality. Use the equals method of String i.e.

if ( userName.equals(getResources().getString(R.string.DB_username)))

Roger that?


It doesn't match when the strings themselves are different objects. You should use

if ( userName.equals(getResources().getString(R.string.DB_username)))

That will compare the actual strings.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号