单击按钮后我的应用程序崩溃

时间:2019-03-03 17:01:33

标签: java android numberformatexception

我对android开发非常陌生,仅具有少量Java编程知识。我需要帮助!我正在制作一个应用程序,它允许您输入花费的金额,并计算出可以花费的金额。它还会跟踪您留在文本文件中的预算。它是使用Java在android studio中制作的。

这是我的错误消息:

2019-03-03 09:42:14.245 4178-4178/? E/SPPClientService: [PackageInfoChangeReceiver] [handlePkgRemovedEvent] PackageName : com.concretegames.budgettracker, true, false
2019-03-03 09:42:27.573 16961-16961/com.concretegames.budgettracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.concretegames.budgettracker, PID: 16961
java.lang.NumberFormatException: s == null
    at java.lang.Integer.parseInt(Integer.java:570)
    at java.lang.Integer.parseInt(Integer.java:643)
    at com.concretegames.budgettracker.MainActivity$1.onClick(MainActivity.java:56)
    at android.view.View.performClick(View.java:6935)
    at android.widget.TextView.performClick(TextView.java:12738)
    at android.view.View$PerformClick.run(View.java:26211)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:7000)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

这是我的代码:

package com.concretegames.budgettracker;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import static java.lang.System.out;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView response = findViewById(R.id.response);
    final Button calc = findViewById(R.id.Calculate);
    Context context = this;
    String filepath = "total_expense.txt";
    String filestoragepath = "MyFileStorage";

    final File edit_file = new File(getExternalFilesDir(filestoragepath), filepath);

            EditText $box = findViewById(R.id.expenses);
    final String $ = $box.getText().toString();

    calc.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            if (edit_file.exists() && !edit_file.isDirectory()) {

                try {

                    FileReader fr = new FileReader(edit_file);
                    BufferedReader br = new BufferedReader(fr);

                    String str;

                    while ((str = br.readLine()) != null) {
                        out.println(str + "\n");
                }

                    br.close();

                    int result = Integer.parseInt(str) - Integer.parseInt($);

                    FileWriter fw = new FileWriter(edit_file);
                    PrintWriter pw = new PrintWriter(fw);

                    pw.print("");
                    pw.print(result);

                    pw.close();

                    response.setText("Budget left over: "+result);

                } catch (IOException e) {
                    out.println("ERROR: " + e.toString());
                    response.setText("ERROR: " + e.toString());
                }
            } else {
                try {
                    edit_file.createNewFile();

                    FileWriter fw = new FileWriter(edit_file);
                    PrintWriter pw = new PrintWriter(fw);

                    pw.print("1500");

                    pw.close();
                } catch (IOException e) {
                    out.println("ERROR: " + e.toString());
                    response.setText("ERROR: " + e.toString());
                }
            }

        }

    });

}
}

P.S。我只有13岁,没有Java经验。我更喜欢HTML,python和javascript。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

Integer.parseInt()如果无法成功将String解析为int,则会引发异常。但是抛出的异常是RuntimeException的子类,因此Java编译器不会强制您捕获该异常。但是仍然强烈建议您一定要抓住它。并且将避免崩溃。通常,在将String解析为int时执行以下操作:

int result;
try {
    result = Integer.parseInt(someString);
} catch (NumberFormatException e) {
    result = 0;
}

答案 1 :(得分:0)

问题在以下行:

int result = Integer.parseInt(str) - Integer.parseInt($);

NumberFormatException是当您尝试将String转换为数字时可能引发的异常。这里的字符串之一为空(我认为str为空)。 当string为null时,Integer.parseInt(null)将无法从null字符串获取整数值。如果字符串包含正确的值,则不会出现此异常。 因此,为避免此异常,请在从字符串中获取整数值之前应用空检查,或将其保留在try catch(NumberFormatException e)中