0

I have an AlertDialog with an EditText inside it:

final EditText et = new EditText(getActivity());
AlertDialog.Builder myDialog = new AlertDialog.Builder(getActivity());
myDialog.setTitle("My Title").setView(et);
myDialog.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        if(et.getText().toString() != ""){
            //Do funny things
        }
    }
});
myDialog.setNegativeButton("Ok",new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
    }
});

My objective is do nothing if the EditText is empty, with nothing i mean nothing. But there are 2 problems:

  1. When click on setPositiveButton, the dialog is closed even if the onClick method is empty.

  2. If EditText is empty i don't know which ASCII character should I match in the if condition. I mean:

    vNombre.getText().toString() == null;
    vNombre.getText().toString() == " ";
    vNombre.getText().toString() == "";
    

This 3 statements return false so I don't know with what I should compare et.getText().toString()

Is there any solution to problem 1 without add custom button to the view of the dialog?

Any ideas for problem 2?

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
SamuelPS
  • 555
  • 6
  • 20
  • You cannot compare strings with `==` operator. In this particular case, I would use `TextUtils.isEmpty(et.getText().toString());` – 1615903 Nov 19 '15 at 11:38
  • http://stackoverflow.com/questions/2620444/how-to-prevent-a-dialog-from-closing-when-a-button-is-clicked – Kuffs Nov 19 '15 at 11:38

4 Answers4

2

Please use equals("") instead of ==

 if(!et.getText().toString().equals("")
{
                   //Do funny things
  }

You can read Java String Compare Example

What's the difference between ".equals" and "=="?

Community
  • 1
  • 1
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
0

You should try to use the below code for checking if a String is empty instead of the above.

if  (!TextUtils.isEmpty(et.getText().toString())) {

}

To not close the dialog when the positive button is clicked you would need to make a custom Dialog there is plenty of SO questions/answers on this already. See here.

Community
  • 1
  • 1
vguzzi
  • 2,420
  • 2
  • 15
  • 19
0

Try this

String gettext = et.getText().toString();

if(!gettext.contentEquals("")){
       //do funny things
}
rajesh dabhi
  • 94
  • 2
  • 6
0

Always check for length of string for checking empty.

int length = ed.getText().toString().trim().length();
if(length > 0)
{
   //do your work here
}
Kuldeep Sakhiya
  • 3,172
  • 1
  • 18
  • 17