You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android销售APP清空txtpay输入框时崩溃问题求助

问题:清空支付输入框时APP崩溃

我是Android Studio开发新手,正在开发一款销售APP。当清空txtpay(对应EditText组件ed5)的文本内容时,APP会崩溃。崩溃发生在afterTextChanged方法的以下代码行:

public void afterTextChanged(Editable s) {
    int subtotal = Integer.parseInt(ed4.getText().toString());
    int pay = Integer.parseInt(ed5.getText().toString());
    int bal = pay - subtotal;
    ed6.setText(String.valueOf(bal));
}

我尝试添加了清空按钮,但问题仍未解决:

clear.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ed5.setText("");
        ed6.setText("");
    }
});

崩溃原因

当清空ed5时,它的文本变成空字符串"",调用Integer.parseInt("")会直接抛出NumberFormatException,导致APP崩溃。而且点击清空按钮后,TextWatcher的afterTextChanged会被触发,执行这段有问题的解析代码。

解决方案

在解析文本为整数之前,先判断输入是否为空或非数字,为空时默认使用0值,或者用try-catch捕获异常。以下是两种可行的处理方式:

方式1:提前校验输入内容

修改afterTextChanged方法,先获取文本并处理空值:

@Override
public void afterTextChanged(Editable s) {
    // 处理subtotal输入,为空则默认0
    String subtotalStr = ed4.getText().toString().trim();
    int subtotal = subtotalStr.isEmpty() ? 0 : Integer.parseInt(subtotalStr);
    
    // 处理pay输入,为空则默认0
    String payStr = ed5.getText().toString().trim();
    int pay = payStr.isEmpty() ? 0 : Integer.parseInt(payStr);
    
    int bal = pay - subtotal;
    ed6.setText(String.valueOf(bal));
}

方式2:使用try-catch捕获异常

如果需要处理非数字输入的情况,可以用try-catch包裹解析逻辑:

@Override
public void afterTextChanged(Editable s) {
    int subtotal = 0;
    int pay = 0;
    
    // 解析subtotal,捕获格式异常
    try {
        subtotal = Integer.parseInt(ed4.getText().toString().trim());
    } catch (NumberFormatException e) {
        subtotal = 0;
    }
    
    // 解析pay,捕获格式异常
    try {
        pay = Integer.parseInt(ed5.getText().toString().trim());
    } catch (NumberFormatException e) {
        pay = 0;
    }
    
    int bal = pay - subtotal;
    ed6.setText(String.valueOf(bal));
}

另外,也可以优化清空按钮的逻辑,避免触发不必要的计算:

clear.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // 暂时移除TextWatcher,避免清空时触发计算
        ed5.removeTextChangedListener(textWatcher);
        ed5.setText("");
        ed6.setText("");
        // 重新添加TextWatcher
        ed5.addTextChangedListener(textWatcher);
    }
});

注意:这种方式需要把TextWatcher提取为成员变量,方便移除和添加。

修改后的完整代码

package com.example.MPOS;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import java.util.ArrayList;

public class Sales extends AppCompatActivity {

    private ArrayList<String> data = new ArrayList<String>();
    private ArrayList<String> data1 = new ArrayList<String>();
    private ArrayList<String> data2 = new ArrayList<String>();
    private ArrayList<String> data3 = new ArrayList<String>();

    private TableLayout table;
    EditText ed1,ed2,ed3,ed4,ed5,ed6;
    Button add,clear;
    ImageView rdash;
    // 提取TextWatcher为成员变量
    private TextWatcher payTextWatcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_sales);

        ed1 = findViewById(R.id.ItemName);
        ed2 = findViewById(R.id.ItemPrice);
        ed3 = findViewById(R.id.ItemQuantity);
        ed4 = findViewById(R.id.txtsub);
        ed5 = findViewById(R.id.txtpay);
        ed6 = findViewById(R.id.txtbalance);
        add = findViewById(R.id.BtnAdd);
        rdash = findViewById(R.id.Left_Icon);
        clear = findViewById(R.id.BtnClear);


        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ed5.removeTextChangedListener(payTextWatcher);
                ed5.setText("");
                ed6.setText("");
                ed5.addTextChangedListener(payTextWatcher);
            }
        });

        rdash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent Left_Icon = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(Left_Icon);
                finish();
            }
        });

        // 初始化TextWatcher
        payTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


            }

            @Override
            public void afterTextChanged(Editable s) {
                String subtotalStr = ed4.getText().toString().trim();
                int subtotal = subtotalStr.isEmpty() ? 0 : Integer.parseInt(subtotalStr);
                
                String payStr = ed5.getText().toString().trim();
                int pay = payStr.isEmpty() ? 0 : Integer.parseInt(payStr);
                
                int bal = pay - subtotal;
                ed6.setText(String.valueOf(bal));
            }
        };

        ed5.addTextChangedListener(payTextWatcher);


        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                add();
            }
        });
    }

    public void add() {
        int tot;

        String prodname = ed1.getText().toString();
        // 这里也添加异常处理,避免输入非数字时崩溃
        int price = 0;
        int qty = 0;
        try {
            price = Integer.parseInt(ed2.getText().toString().trim());
            qty = Integer.parseInt(ed3.getText().toString().trim());
        } catch (NumberFormatException e) {
            // 可添加Toast提示用户输入有效数字
            return;
        }
        tot = price * qty;

        data.add(prodname);
        data1.add(String.valueOf(price));
        data2.add(String.valueOf(qty));
        data3.add(String.valueOf(tot));

        TableLayout table = findViewById(R.id.tb1);
        TableRow row = new TableRow (this);
        TextView t1 = new TextView(this);
        TextView t2 = new TextView(this);
        TextView t3 = new TextView(this);
        TextView t4 = new TextView(this);

        int sum = 0;
        for(int i = 0; i< data.size(); i ++) {
            String pname = data.get(i);
            String pprice = data1.get(i);
            String pqty = data2.get(i);
            String total = data3.get(i);

            t1.setText(pname);
            t2.setText(pprice);
            t3.setText(pqty);
            t4.setText(total);

            sum += Integer.parseInt(total);
        }

        row.addView(t1);
        row.addView(t2);
        row.addView(t3);
        row.addView(t4);
        table.addView(row);

        ed4.setText(String.valueOf(sum));
        ed1.setText("");
        ed2.setText("");
        ed3.setText("");

        ed1.requestFocus();
    }
}

内容的提问来源于stack exchange,提问作者Huncho.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:57:05