如何处理 edittext OntextChanged 中的数字格式异常

How to handle Number Format Exception in edittext OntextChanged

我在我的应用程序中编辑了文本来操纵产品数量,但如果我要更改数量,那会出现 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) {

                }
            });

当您删除 editText 上的所有内容时,editText 将 return 为空字符串。因此你会得到 NPENumber 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
}

看看这个

使用trycatch

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();
}
@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
    }
}