I just can not understand the reason:

String name = null; public void onClickButton(View view){ //Нажимается кнопка name = mAutoComplete.getText().toString();//в переменную помещается } // результат до этого она пустая public void onClickPhoto(View view) {// верхняя кнопка появляется после нажатия на эту mAutoComplete.setVisibility(AutoCompleteTextView.VISIBLE); button3.setVisibility(Button.VISIBLE); if (name != null) {выполняющийся код}//если переменная не равна 0 } 

But when you click on onClickPhoto, the program immediately goes to the execution of the code in curly brackets of the condition, why is it empty ???

  • Try this if(!Objects.equals(name, null)) {твой код} - E1mir
  • one
    Vryatli in this case, but do not assign listeners clicks in the markup - do it programmatically. - Yuriy SPb

1 answer 1

The fact is that mAutoComplete.getText().toString() returns an empty string if nothing is entered in the field. Need to do either so

 String text = mAutoComplete.getText().toString(); if(text.isEmpty()) { // какой-то код } 

either so

 String text = mAutoComplete.getText().toString(); if(TextUtils.isEmpty(text)) { // какой-то код } 

The second option is safer, because it first checks the value for null , and then for isEmpty()