1

I am trying to enable positivebutton of an AlertDialog only when text are set in both editText field, but this is not working, i.e. PositiveButton does not show up even when I have text in both field.

Of course, if I don't have text in both field, I am getting error NumberFormatException: empty String

  case R.id.action_geolocate:
    AlertDialog.Builder placePicker = new AlertDialog.Builder(this);
    LayoutInflater li = LayoutInflater.from(this);
    final View view = li.inflate(R.layout.fragment_place, null);
    placePicker.setView(view);
    placePicker.setTitle("Enter Latitude and Longitude");
    final EditText lat2 = view.findViewById(R.id.lati2);
    final EditText long2 = view.findViewById(R.id.longi2);
    if (lat2.getText().toString().length()>0 && long2.getText().toString().length()>0) {
      placePicker.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          Lat = Double.parseDouble(lat2.getText().toString());
          Long = Double.parseDouble(long2.getText().toString());
          setupViewPager();
        }
      });
    }
    placePicker.setNegativeButton("Cancel", null);
    placePicker.show();
    return true;

Update

        placePicker.setNegativeButton("Cancel", null);
        AlertDialog pp = placePicker.create();

        pp.show();
        pp.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
        if (!TextUtils.isEmpty(lat2.getText().toString())){
          pp.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
        }
        return true;
BaRud
  • 3,055
  • 7
  • 41
  • 89

2 Answers2

0

Before checking the length of your Strings, verify they aren't null : if ((lat2.getText()!=null) && (long2.getText()!=null)) { if (lat2.getText().toString().length()>0 && long2.getText().toString().length()>0) {...

Zelig63
  • 1,592
  • 1
  • 23
  • 40
  • that does not change any thing. which is understandable. if this is null, I may have null point exception, but that has nothing to do with visibility. Also, I am yet to find an exemple of set with non zero length, but null. – BaRud Feb 09 '20 at 06:05
0

Make a custom Dialog instead of AlertDialog. In the XML view, set visibility attribute to the positive button to "gone". Then, in the java code setting up the Dialog, setup .addTextChangedListener() to the EditText views and in those listeners, check the length of the string entered and you can decide when to call positiveButton.visibility(View.VISIBLE); to make the positive button appear.

DevJZ
  • 100
  • 8