我已经在我的应用程序中编辑了文本来操纵产品数量,但是如果我要更改数量的问题,那时候会获得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) {
}
});
答案 0 :(得分:2)
使用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();
}
答案 1 :(得分:1)
当您删除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
}
答案 2 :(得分:0)
@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
}
}