android - 从 EditText 获取数据输入时,导致应用程序崩溃 Android 的 NumberFormat 错误

标签 android parsing crash android-edittext number-formatting

我正在尝试获取用户输入,然后将它们解析为 double 。我什至添加了一种方法来检查它们是否为空,然后将它们设置为 0,但它仍然崩溃并给我错误。

这是我的代码:

package com.example.alexlevine.oceanapp;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CarbonCalcActivity extends AppCompatActivity {

    //household energy
    double electricity;
    double naturalGas;
    double fuelOil;
    double propane;

    EditText elecunit;
    EditText elecbill;
    EditText gasunit;
    EditText gasbill;
    EditText fuelunit;
    EditText fuelbill;
    EditText propunit;
    EditText propbill;
    //transportation
    double vehicle1;
    double vehicle2;
    double vehicle3;
    double publicTransport;//.42*number of miles
    double airTravel;

    EditText v1mpw;
    EditText v1mpg;
    EditText v2mpw;
    EditText v2mpg;
    EditText v3mpw;
    EditText v3mpg;
    EditText pub;
    EditText air;
    //food
    double totalFood;
    double meatFishEggs;
    double cerealBakery;
    double dairy;
    double fruitVegetable;
    double eatingOut;
    double otherFoods;

    EditText meat;
    EditText cer;
    EditText da;
    EditText fv;
    EditText out;
    EditText otherf;
    //services and goods
    double totalSG;
    double clothing;
    double furnishHousehold;
    double otherGoods;
    double services;

    double total;

    EditText sg;
    EditText cloth;
    EditText furn;
    EditText otherg;
    EditText serv;
    Button submit;

    List<double[]> dataValues;

    Context activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_carbon_calc);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        /*
        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(getString(R.string.saved_high_score), newHighScore);
        editor.commit();*/

        activity = CarbonCalcActivity.this;

        dataValues= new ArrayList<double[]>();

        submit = (Button) findViewById(R.id.submitb);

    }

    public void onBtnClicked(View v){
        if(v.getId() == R.id.submitb){
            elecunit = (EditText) findViewById(R.id.kwh);
            elecbill = (EditText) findViewById(R.id.elec);
            if(elecunit != null && elecbill != null) {
                electricity = (Integer.parseInt(elecbill.getText().toString())/Integer.parseInt(elecunit.getText().toString()))*1.37*12;

            }
            else
                electricity = 0;

            gasunit = (EditText) findViewById(R.id.cf);
            gasbill = (EditText) findViewById(R.id.gas);

            if(gasunit != null && gasbill != null) {
                naturalGas = (Integer.parseInt(gasbill.getText().toString())/Integer.parseInt(gasunit.getText().toString()))*120.61*12;

            }
            else
                naturalGas = 0;

            fuelunit = (EditText) findViewById(R.id.fogal);
            fuelbill = (EditText) findViewById(R.id.fo);

            if(fuelunit != null && fuelbill != null) {
                fuelOil = (Integer.parseInt(fuelbill.getText().toString())/Integer.parseInt(fuelunit.getText().toString()))*22.37*12;

            }
            else
                fuelOil = 0;

            propunit = (EditText) findViewById(R.id.progal);
            propbill = (EditText) findViewById(R.id.pro);

            if(propunit != null && propbill != null) {
                propane = (Integer.parseInt(propbill.getText().toString())/Integer.parseInt(propunit.getText().toString()))*12.17*12;

            }
            else
                propane = 0;

            v1mpg = (EditText) findViewById(R.id.v1mpg);
            v1mpw = (EditText) findViewById(R.id.v1mpw);

            if(v1mpg != null && v1mpw != null) {
                vehicle1 = ((Integer.parseInt(v1mpw.getText().toString())*52)/(Integer.parseInt(v1mpg.toString()))*19.4*(100/95));
            }
            else {
                vehicle1 = 0;
            }

            v2mpg = (EditText) findViewById(R.id.v2mpg);
            v2mpw = (EditText) findViewById(R.id.v2mpw);

            if(v2mpg != null && v2mpw != null) {
                vehicle2 = ((Integer.parseInt(v2mpw.getText().toString())*52)/Integer.parseInt(v2mpg.toString()))*19.4*(100/95);
            }
            else {
                vehicle2 = 0;
            }

            v3mpg = (EditText) findViewById(R.id.v3mpg);
            v3mpw = (EditText) findViewById(R.id.v3mpw);

            if(v3mpg != null && v3mpw != null) {
                vehicle3 = ((Integer.parseInt(v3mpw.getText().toString())*52)/Integer.parseInt(v3mpg.toString()))*19.4*(100/95);
            }
            else {
                vehicle3 = 0;
            }

            pub = (EditText) findViewById(R.id.pubmpy);

            if(pub != null) {
                publicTransport = (Integer.parseInt(pub.toString()))*.42;

            }
            else
                publicTransport = 0;

            air = (EditText) findViewById(R.id.airmpy);

            if(air != null) {
                airTravel = (Integer.parseInt(air.toString()))*223*1.2*1.9*.0022;

            }
            else
                airTravel = 0;

            meat = (EditText) findViewById(R.id.meat);

            if(meat != null) {
                meatFishEggs = (Integer.parseInt(meat.toString()))*1452*12*.0022;

            }
            else
                meatFishEggs = 0;

            cer = (EditText) findViewById(R.id.cereal);

            if(cer != null) {
                cerealBakery = (Integer.parseInt(cer.toString()))*741*12*.0022;

            }
            else
                cerealBakery = 0;

            da = (EditText) findViewById(R.id.dairy);

            if(da != null) {
                dairy = (Integer.parseInt(cer.toString()))*1911*12*.0022;

            }
            else
                dairy = 0;

            fv = (EditText) findViewById(R.id.fruit);

            if(fv != null) {
                fruitVegetable = (Integer.parseInt(fv.toString()))*1176*12*.0022;

            }
            else
                fruitVegetable = 0;

            out = (EditText) findViewById(R.id.out);

            if(out != null) {
                eatingOut = (Integer.parseInt(out.toString()))*368*12*.0022;

            }
            else
                eatingOut = 0;

            otherf = (EditText) findViewById(R.id.otherf);

            if(otherf != null) {
                otherFoods = (Integer.parseInt(otherf.toString()))*467*12*.0022;

            }
            else
                otherFoods = 0;

            totalFood = meatFishEggs+cerealBakery+dairy+fruitVegetable+eatingOut+otherFoods;

            cloth = (EditText) findViewById(R.id.cloth);

            if(cloth != null) {
                clothing = (Integer.parseInt(cloth.toString()))*436*12*.0022;

            }
            else
                clothing = 0;

            furn = (EditText) findViewById(R.id.furnish);

            if(furn != null) {
                furnishHousehold = (Integer.parseInt(furn.toString()))*459*12*.0022;

            }
            else
                furnishHousehold = 0;

            otherg = (EditText) findViewById(R.id.otherg);

            if(otherg != null) {
                otherGoods = (Integer.parseInt(otherg.toString()))*338*12*.0022;

            }
            else
                otherGoods = 0;

            serv = (EditText) findViewById(R.id.serv);

            if(serv != null) {
                services = (Integer.parseInt(serv.toString()))*178*12*.0022;

            }
            else
                services = 0;

            totalSG = clothing + furnishHousehold + otherGoods + services;

            Date currentTime = Calendar.getInstance().getTime();

            double[] currentData = new double[26];

            currentData[0] = currentTime.getMonth();
            currentData[1] = currentTime.getDate();
            currentData[2] = currentTime.getYear();
            currentData[3] = electricity;
            currentData[4] = naturalGas;
            currentData[5] = fuelOil;
            currentData[6] = propane;
            currentData[7] = electricity;
            currentData[8] = vehicle1;
            currentData[9] = vehicle2;
            currentData[10] = vehicle3;
            currentData[11] = publicTransport;
            currentData[12] = airTravel;
            currentData[13] = totalFood;
            currentData[14] = meatFishEggs;
            currentData[15] =cerealBakery;
            currentData[16] = dairy;
            currentData[17] = fruitVegetable;
            currentData[18] = eatingOut;
            currentData[19] = otherFoods;
            currentData[20] = totalSG;
            currentData[21] = clothing;
            currentData[22] = furnishHousehold;
            currentData[23] = otherGoods;
            currentData[24] = services;

            total = 0;

            for(int i = 3; i < 25; i++)
            {
                total = total + currentData[i];
            }

            currentData[25] = (total/2000);

        }
    } 

这是我的日志:
08-31 18:51:25.778 17735-17735/com.example.alexlevine.oceanapp 
    E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.example.alexlevine.oceanapp, PID: 17735

java.lang.IllegalStateException: Could not execute method for 
android:onClick

at 
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener
.onClick(AppCompatViewInflater.java:293)

at android.view.View.performClick(View.java:6219)

at android.view.View$PerformClick.run(View.java:24482)

at android.os.Handler.handleCallback(Handler.java:769)

at android.os.Handler.dispatchMessage(Handler.java:98)

at android.os.Looper.loop(Looper.java:164)

at android.app.ActivityThread.main(ActivityThread.java:6540)

at java.lang.reflect.Method.invoke(Native Method)

at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Caused by: java.lang.reflect.InvocationTargetException

at java.lang.reflect.Method.invoke(Native Method)

at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener
.onClick(AppCompatViewInflater.java:288)

at android.view.View.performClick(View.java:6219) 

at android.view.View$PerformClick.run(View.java:24482) 
                                                                                     at android.os.Handler.handleCallback(Handler.java:769) 
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:98) 
                                                                                     at android.os.Looper.loop(Looper.java:164) 
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:6540) 
                                                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                                                     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
                                                                                  Caused by: java.lang.NumberFormatException: For input string: ""
                                                                                     at java.lang.Integer.parseInt(Integer.java:620)
                                                                                     at java.lang.Integer.parseInt(Integer.java:643)
                                                                                     at com.example.alexlevine.oceanapp.CarbonCalcActivity.onBtnClicked(CarbonCalcActivity.java:115)
                                                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                                                                                     at android.view.View.performClick(View.java:6219) 
                                                                                     at android.view.View$PerformClick.run(View.java:24482) 
                                                                                     at android.os.Handler.handleCallback(Handler.java:769) 
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:98) 
                                                                                     at android.os.Looper.loop(Looper.java:164) 
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:6540) 
                                                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                                                     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

我不确定造成这种情况的确切原因,特别是因为我做了所有的空检查。有人可以帮助解决错误吗?谢谢!
elecunit = (EditText) findViewById(R.id.kwh);
elecbill = (EditText) findViewById(R.id.elec);
            String elecunitString = elecunit.getText().toString();
            String elecbillString = elecbill.getText().toString();

            if(elecunitString != "" && elecbillString != "") {
                electricity = (Integer.parseInt(elecbill.getText().toString())/Integer.parseInt(elecunit.getText().toString()))*1.37*12;

            }
            else
                electricity = 0; 

最佳答案

我注意到的是,您要检查的 null 是 EditText 本身,而不是 EditText 的值。您正在这样做。

 EditText editText = (EditText) findViewById(R.id.edittext);
 if(editText != null) {
     value = Double.parseDouble(editText.getText().toString());
 } else {
     value = 0;
 }

所以检查edittext值的正确方法..这样做
 EditText editText = (EditText) findViewById(R.id.edittext);
 String etString = editText.getText().toString();
 if(etString.equals("")) {
     value = Double.parseDouble(etString);
 } else {
     value = 0;
 }

还要检查字符串是否可以转换,因为也许你正在转换一个字母,你会得到一个 NumberFormatException 所以你可以做这样的事情
private double parseStringToDouble(String sVal) {
    if(!sVal.equals("")) {
            try {
                return Double.parseDouble(sVal);
            } catch(Exception e) {
                //will handle the exception
                return 0;
            }
    }
    else return 0;
}

并从您的编辑文本中获取值(value)
EditText et1 = (EditText) findViewById(R.id.et1);
value1 = parseStringToDouble(et1.getText().toString());

EditText et2 = (EditText) findViewById(R.id.et2);
value2 = parseStringToDouble(et2.getText().toString());

关于android - 从 EditText 获取数据输入时,导致应用程序崩溃 Android 的 NumberFormat 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45992393/

相关文章:

java - Android 仪器测试、模拟 final类

parsing - LR(1) 解析器中的左递归

android - 错误 : cannot find symbol class GoogleAccountCredential

android - 如何在 Android 中使 View 不可见/消失 onBackPressed() 方法?

java - 在 joda time 中使用 parseDateTime 时休息 1 天

parsing - 从单个字符串有效地计算统计数据(bowtie2 的 bam 文件)

java - 什么会导致崩溃时不创建 hs_err_pid 文件?

c++ - 如何封装一个线程?

memory-management - 如何解决 iOS 6 上 Map 的内存问题

android - 在 Android 上获取相机信息的 API