简体   繁体   中英

the EditText is empty and the method always returns true?

Any idea why this method isTopicExist() posted below always returns true;

in the code below, i am checking is the EditText has a text or not by calling he method isTopicExist , but at run time, i do not enter any text and press the button and i expect to see the toast in the else statement, but the toast never shows and the if (isTopicExist() && (getSelectedRB() != -1)) is always true .

I am missing somethin?

code

@Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (isTopicExist() && (getSelectedRB() != -1)) {
                Log.d(TAG, "Topic: "+et_topic.getText().toString());
                Log.d(TAG, "QoS_Level: "+getSelectedRB());
                subscription_topic = et_topic.getText().toString();
                subscription_QoS = getSelectedRB();
            }else {
                Toast.makeText(getActivity(), "Topic is a mandatory field", Toast.LENGTH_LONG).show();
            }
        }
        private boolean isTopicExist() {
            // TODO Auto-generated method stub
            if (et_topic.getText().equals(""))
                return false;
                return true;
        }
    });

Change your if statement as follows:

 if (et_topic.getText().toString().trim().equals(""))

EditText#getText() returns an Editable object, which won't be equal to "" .

try this:

private boolean isTopicExist() 
{
            // TODO Auto-generated method stub
            if (et_topic.getText().toString().trim().equalsIgnoreCase(""))
                return false;

                return true;
        }
    });

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