Search code examples
androidpreference

NumberFormatException with IntEditTextPreference


In my android application, I'm using a class called 'IntEditTextPreference'. This class is used when I want a user to introduce a preference as an integer.

But it has a problem. When the user leaves the field empty and press "ok", an NumberFormatException is thrown.

What could I do to avoid the user to press "ok" when the field is empty?

Thanks!

public class IntEditTextPreference extends EditTextPreference
{

   public IntEditTextPreference(Context context)
   {
           super(context);
   }

   public IntEditTextPreference(Context context, AttributeSet attrs)
   {
       super(context, attrs);
   }

   public IntEditTextPreference(Context context, AttributeSet attrs, int defStyle)
   {
       super(context, attrs, defStyle);
   }

   @Override
   protected String getPersistedString(String defaultReturnValue)
   {
        return String.valueOf(getPersistedInt(-1));
   }

   @Override
   protected boolean persistString(String value)
   {
       return persistInt(Integer.valueOf(value));
   }

}


Solution

  • You should probably still have a try/catch block around it to catch NumberFormatException. But there are many ways to do this. One way is you can use the buttons setClickable method to false and then true when the text is not null and is integer using onTextChangedListener. Or you could simply let it be clickable but check for empty string or non-integer when the button is clicked and use a warning message toast/alert/label to let the user know they have incorrect field before allowing the button to do anything else. Hope this helps!