Reputation: 63
I'm getting integers of two EditText and on one of them textWatch is applied, multiplying them and setting text to another EditText. it normally works fine but when one of edit field become empty while hitting backspace app crashes.
protected final TextWatcher getValueWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
int qty = Integer.parseInt(s.toString());
int unitPrice = Integer.parseInt(unitPriceEdit.getText().toString());
if (s.length() > 0)
totalPriceEdit.setText(String.valueOf(qty * unitPrice));
}
public void afterTextChanged(Editable s) {
}
};
Logcat
java.lang.NumberFormatException: Invalid int: "" at
java.lang.Integer.invalidInt(Integer.java:138) at
java.lang.Integer.parseInt(Integer.java:358) at
java.lang.Integer.parseInt(Integer.java:334) at
com.example.fani.project.MainActivity$2.onTextChanged(MainActivity.java:90)
at android.widget.TextView.sendOnTextChanged(TextView.java:7679) at
android.widget.TextView.handleTextChanged(TextView.java:7739)
Upvotes: 0
Views: 993
Reputation: 1240
Modify your onTextChanged():
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0){
int qty = Integer.parseInt(s.toString());
int unitPrice = Integer.parseInt(unitPriceEdit.getText().toString());
totalPriceEdit.setText(String.valueOf(qty * unitPrice));
}
}
Upvotes: 1
Reputation: 147
null pointer error occurs due to s.length > 0
Change this in your code.
if (s.length() > 0)
totalPriceEdit.setText(String.valueOf(qty * unitPrice));
}
TO
if(s != null){
if (s.length() > 0)
totalPriceEdit.setText(String.valueOf(qty * unitPrice));
}
}
Upvotes: 0
Reputation: 14810
Replace your code as below
protected final TextWatcher getValueWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0){
int qty = Integer.parseInt(s.toString());
int unitPrice = Integer.parseInt(unitPriceEdit.getText().toString());
totalPriceEdit.setText(String.valueOf(qty * unitPrice));
}
}
public void afterTextChanged(Editable s) {
}
};
Check the length of your string before parsing it..
Upvotes: 3