简体   繁体   中英

Method returns wrong value - Android

Why does this method always return true, even when the editTexts have nothing in them?

private boolean allFieldsFilledOut() {
        boolean allFieldsFilledOut = false;
        EditText name = (EditText) findViewById(R.id.editTextName);
        EditText passWord = (EditText) findViewById(R.id.editTextPassWord);
        EditText image = (EditText) findViewById(R.id.editTextProfilePicture);

        if (name.getText().toString() != "" && passWord.getText().toString() != ""
            && image.getText().toString() != "") {
            allFieldsFilledOut = true;
        }
        else {
            allFieldsFilledOut = false;
        }

        return allFieldsFilledOut;
    }

One thing I have been wondering about is, I create this activity through an intent a few times per use case. Am I referencing an old activity's editTexts? Should I be killing the activity when show a new activity? findViewById(R.id.editTextName) gets the application resource, with no reference to this specific activity. Is there another way to reference these editTexts?

When you compare string, use equals is compare string's value, use == is compare string's address

this mean (name.getText().toString())'s address != ("")'s address so that it always true

name.getText().toString() != ""

if you want to compare string's value, you need to use equals

if (name.getText().toString().equals("") == false && 
    passWord.getText().toString().equals("") == false && 
    image.getText().toString().equals("") == false)

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