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

1

Hello everyone, I'm developing an application where the user must enter a quantity and the unit value and the application calculates the total to pay. But if you erase all the value that is in the fields the program aborts. How can I fix this?

Include ProductActivity.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());
        }
    });
}
}
    
asked by anonymous 25.02.2017 / 03:13

2 answers

2

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

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

To resolve, 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 must also ensure that the user only types numbers in EditText. Include in the EditText declaration the following:

android:text="0" 
android:inputType="numberDecimal"
    
25.02.2017 / 15:05
-2

Apparently the error is in this section:

valorTotal.setText(total.toString());

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

valorTotal.setText(String.valueOf(total));
    
25.02.2017 / 03:34