How to consider an empty EditText as “0”

Posted on

Question :

I’m developing an Android app that calculates 3×3 arrays
so I have 18 EditText , however if I want to multiply an array 2×3, 2×2, 1×2, etc. I would have to fill the fields the size of the array and leave the other fields with 0 and this would not change the result.

I made a condition for it to notify if the field is empty but it would be better to consider the empty field as “0” without requiring the user to fill in all fields

    

Answer :

This can be easily accomplished by declaring your EditText with its default value equal to zero and indicating that it can only receive numeric values:

<EditText
   android_id="@+id/edittext"
   android_layout_width="fill_parent"
   android_layout_height="wrap_content"
   android_text="0" 
   android_inputType="number"/>

The android: text=”0″ attribute assigns the value zero as default value.
The android: inputType=”number” attribute causes only integer values to be accepted by EditText

    

To get the value of your EditText , use this function by passing it as a parameter

private int getValorEdit(EditText edit){

    int ret = 0;

    if (! edit.getText().toString().equalsIgnoreCase("")) {
        ret = Integer.valueOf(edit.getText().toString());
    }   
    return ret;

}

Wait for help.

    

None of the above corrections worked for me.
Just this:

if(txtEdit.getText().toString().equals("")){
  num = 0;
} else {
  num = parseInt(txtEdit.getText().toString());
}

    

Leave a Reply

Your email address will not be published. Required fields are marked *