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

Android应用点击Add按钮崩溃:EditText数值相加更新TextView问题

Android应用点击Add按钮崩溃问题解决

崩溃根源分析

  • 空字符串解析异常:首次启动时SharedPreferences无保存数据,ergebnis文本为空,调用Integer.parseInt("")会触发NumberFormatException;若zahl1未输入内容,解析空字符串也会引发同样崩溃。
  • 冗余代码引发异常:需求明确要求忽略zahl2,但代码中仍对其进行解析,无意义且会在zahl2为空时触发崩溃。

修复后的完整代码

Java代码

package com.example.rechnen_speichern;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

    Button save, addieren;
    EditText zahl1, zahl2;
    TextView ergebnis;
    String finalergebnis;
    SharedPreferences sp;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        save = findViewById(R.id.btnsave);
        addieren = findViewById(R.id.btnadd);
        zahl1 = findViewById(R.id.eingabe1);
        zahl2 = findViewById(R.id.eingabe2);
        ergebnis = findViewById(R.id.ergebnis);

        sp = getSharedPreferences("myergebnis", Context.MODE_PRIVATE);
        editor = sp.edit();

        // 初始化时给默认值0,避免空字符串
        String data = sp.getString("key", "0");
        ergebnis.setText(data);

        addieren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int z1 = 0;
                // 处理Zahl1的输入,非空且有效才解析
                if (!zahl1.getText().toString().trim().isEmpty()) {
                    try {
                        z1 = Integer.parseInt(zahl1.getText().toString().trim());
                    } catch (NumberFormatException e) {
                        Toast.makeText(MainActivity.this, "请输入有效数字", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                int z2 = 0;
                // 处理ergebnis的文本,防止解析异常
                if (!ergebnis.getText().toString().trim().isEmpty()) {
                    try {
                        z2 = Integer.parseInt(ergebnis.getText().toString().trim());
                    } catch (NumberFormatException e) {
                        z2 = 0;
                    }
                }

                int z3 = z1 + z2;
                ergebnis.setText(String.valueOf(z3));
            }
        });

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finalergebnis = ergebnis.getText().toString();
                editor.putString("key", finalergebnis);
                editor.apply();
                Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

XML代码(无需修改)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ergebnis"
        android:textSize="50sp"
        android:layout_gravity="center"
       />

    <EditText
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:id="@+id/eingabe1"
        android:hint="Zahl 1"
        />
    <EditText
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:id="@+id/eingabe2"
        android:hint="Zahl 2"/>

    <Button
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:id="@+id/btnadd"
        android:text="Addieren"/>
    <Button
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:id="@+id/btnsave"
        android:text="Save"/>

</LinearLayout>

关键修改说明

  1. 初始化默认值:将SharedPreferences的默认返回值从空字符串改为"0",确保ergebnis始终有可解析的数字文本。
  2. 移除冗余解析:删除对zahl2的解析代码,符合需求要求。
  3. 异常防护:对输入和文本添加非空判断,并用try-catch捕获数字格式异常,同时给用户错误提示,彻底避免崩溃。
  4. 输入去空格:使用trim()处理输入文本,避免用户输入空格导致的解析失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:34:52