How to calculate a value while the user types in an Android application?

Asked

Viewed 496 times

1

Hello folks I am developing an application in which the user must enter a quantity and the unit value and the application calculates the total payable. But if you delete all the value that is in the fields the program aborts. How can I fix this?

Incluprodutoactivity.java

public class IncluirProdutoActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_incluir_produto);

    final EditText quantidade = (EditText) findViewById(R.id.quantidade);
    final EditText precoUnitario = (EditText) findViewById(R.id.preco_unitario);
    final EditText valorTotal = (EditText) findViewById(R.id.valor_total);



    quantidade.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}

        @Override
        public void afterTextChanged(Editable s) {
            Float preco = Float.valueOf(precoUnitario.getText().toString());
            Float q = Float.valueOf(s.toString());
            Float total = q * preco;
            valorTotal.setText(total.toString());
        }
    });
}
}

2 answers

2


When deletes the value in the fields the string returned by precoUnitario.getText().toString() is empty("").

An empty string cannot be converted to a Float, so an error is generated.

To solve you should check this situation and do the calculation using the value zero:

@Override
public void afterTextChanged(Editable s) {
    Float preco = 0;
    Float q = 0;

    String stringPreco = precoUnitario.getText().toString().trim();
    if(!stringPreco.equals("")){
        preco = Float.valueOf(stringPreco);
    }

    String stringS = s.toString().trim();
    if(!stringS.equals("")){   
        q = Float.valueOf(stringS);
    }         

    Float total = q * preco;
    valorTotal.setText(total.toString());
}

Note that you should also ensure that the user only type numbers in Edittext.
Include in the Edittext statement the following:

android:text="0" 
android:inputType="numberDecimal"

-2

Apparently the error is in that stretch:

valorTotal.setText(total.toString());

instead of converting this way try to change this line to:

valorTotal.setText(String.valueOf(total));

Browser other questions tagged

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