How to consider an empty Edittext as "0"

Asked

Viewed 797 times

3

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

I made a condition for him to warn if the field is empty but the best thing would be for him to consider the empty field as "0" without needing the user to fill in all fields

3 answers

3

This can easily be achieved by declaring your Edittext with its default value equal to zero and indicate that it can only receive numerical values:

<EditText
   android:id="@+id/edittext"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="0" 
   android:inputType="number"/>

The attribute android:text="0" sets zero as default.
The attribute android:inputType="number" only integers are accepted by Edittext

  • Obgd, but if Usario deletes "0" the app will crash I need the app to consider the empty field as the number "0"

  • When this happens the correct, as you say you are already doing, is to warn the user,

  • Note that now no longer obliges the user to fill in all fields, the zero will appear by default.

  • I did what you said in every field. And I created an if that if I have an empty field it shows a warning instead of calculating, then it does not crash, it was a good temporary solution, but if someone has a hint of how to calculate the null field as 0 I am very grateful

1

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

private int getValorEdit(EditText edit){

    int ret = 0;

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

}

Hope to help you.

  • I did it, but it is still null instead of sending the number "0"

1

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.