我在我的应用程序中编辑了文本来操纵产品数量,但是如果我更改数量,那么问题就是获得NPE。 更改编辑文本中的数量 我需要删除现有的,需要添加一个新的,请检查以下代码
viewHolder.edt_product_qty.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
quantity_count= Integer.parseInt(viewHolder.edt_product_qty.getText().toString());
buyNowList(user_id,"UserCart",0,stList.get(position).getCartList1().getId(),stList.get(position).getCartList1().getProdSku(),stList.get(position).getCartList1().getProdId(),quantity_count,0,qty_status,stList.get(position).getCartList1().getProdPrice());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
使用 try
和 catch
块
try {
quantity_count = Integer.parseInt(viewHolder.edt_product_qty.getText().toString());
buyNowList(user_id,"UserCart",0,stList.get(position).getCartList1().getId(),stList.get(position).getCartList1().getProdSku(),stList.get(position).getCartList1().getProdId(),quantity_count,0,qty_status,stList.get(position).getCartList1().getProdPrice());
} catch (NumberformatException e) {
e.printStackTrace();
}
当您删除 editText 上的所有内容时,editText 将返回一个空字符串。因此,您将获得NPE
,也Number Format Exception
。
你可以这样处理:
if(!viewHolder.edt_product_qty.getText().toString().equals("")){
quantity_count= Integer.parseInt(viewHolder.edt_product_qty.getText().toString());
buyNowList(user_id,"UserCart",0,stList.get(position).getCartList1().getId(),stList.get(position).getCartList1().getProdSku(),stList.get(position).getCartList1().getProdId(),quantity_count,0,qty_status,stList.get(position).getCartList1().getProdPrice());
}
将初始值与当前值进行比较
首先,您需要在 beforeTextChanged
中分配一个变量作为初始值。
initalValue =viewHolder.edt_product_qty.getText().toString();
然后在onTextChanged
:
if(!viewHolder.edt_product_qty.getText().toString().equals("")){
quantity_count = Integer.parseInt(viewHolder.edt_product_qty.getText().toString()); //
}if(initalValue>quantity_count)
{
// code
}else
{
//code
}
看看这个 https://stackoverflow.com/a/20278708/5156075
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
try {
quantity_count = Integer.parseInt(viewHolder.edt_product_qty.getText().toString());
buyNowList(user_id, "UserCart", 0, stList.get(position).getCartList1().getId(), stList.get(position).getCartList1().getProdSku(), stList.get(position).getCartList1().getProdId(), quantity_count, 0, qty_status, stList.get(position).getCartList1().getProdPrice());
} catch (NumberFormatException e) {
// maybe show some information to user in case of exception
}
}