Domanda

I have a TextView that calculates two EditText. It works as long as a digit is in the EditText but as soon all numbers are deleted I get this error

java.lang.NumberFormatException: unable to parse '' as integer

I understand why I'm getting the error but I cant figure out how to fix it. I've googled and searched for answers on this site but they don't seem to work for my situation. I've tried to catch the NumberFormatException but I cant do it. Any help?

items = (EditText)findViewById(R.id.items);
itemcost = (EditText)findViewById(R.id.itemcost);
inventoryvalue = (TextView)findViewById(R.id.inventoryvalue);


TextWatcher textWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
calculateResult();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
};

items.addTextChangedListener(textWatcher);
itemcost.addTextChangedListener(textWatcher);
}

private void calculateResult() throws NumberFormatException {

String s1 = items.getText().toString();
    String s2 = itemcost.getText().toString();
    int value1 = Integer.parseInt(s1);
    int value2 = Integer.parseInt(s2);
    int result = value1 * value2; {

// Calculates the result
result = value1 * value2;
// Displays the calculated result
inventoryvalue.setText(String.valueOf(result));             
}
È stato utile?

Soluzione

Check if your String contains only number:

s1 = s1.trim();
if (s1.matches("[0-9]+") {
 value1 = Integer.parseInt(s1);
}

Altri suggerimenti

in the calculateResult method put everythin in an if block:

if(items.getText().tostreing().length>0 && itemcost.getText().toString().length>0){
//your current method definition
}

Change your afterTextChanged method to:

public void afterTextChanged(Editable s) {
  if (s.length > 0)
      calculateResult();
}

In calculateResult() you do Integer.parseInt(s1); without checking if String s1 or s2 are empty?

Thus you cant convert an empty String to Int. Try checking if s1 or s2 are empty before trying to convert them to Integers and calculating with them...

You can use : .equals(String s) to check if Strings are equal to others.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top