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

Posted

技术标签:

【中文标题】从 EditText 获取数据输入时,导致应用程序崩溃 Android 的 NumberFormat 错误【英文标题】:NumberFormat Error Causing App to Crash Android When Taking Data Inputs From EditText 【发布时间】:2017-09-01 02:01:56 【问题描述】:

我正在尝试获取用户输入,然后将它们解析为双精度数。我什至添加了一种方法来检查它们是否为空,然后将它们设置为 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) 

我不确定造成这种情况的确切原因,特别是因为我已经完成了所有 null 检查。有人可以帮助解决错误吗?谢谢! 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; 

【问题讨论】:

对从 EditText 捕获的 String 在 Parse 到 Integer 之前应用适当的验证,在您的情况下,字符串可能为空。 【参考方案1】:

我注意到的是,您正在检查 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;

并从您的编辑文本中获取价值

EditText et1 = (EditText) findViewById(R.id.et1);
value1 = parseStringToDouble(et1.getText().toString());

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

【讨论】:

我在您最初的建议中添加了内容,并将 EditText 更改为在获取输入时仅显示数字键盘,因此无法输入字母。但是,我仍然遇到同样的错误。我将新代码添加到原始问题中。 是 IllegalStateException 吗?我可以看看你的 xml 吗? 请再次检查..这就是你在做什么.. if(elecunitString != "" && elecbillString != "") 因为你正在检查一个字符串..你应该使用 if(elecunitString .equals("") && elecbillString.equals(""))

以上是关于从 EditText 获取数据输入时,导致应用程序崩溃 Android 的 NumberFormat 错误的主要内容,如果未能解决你的问题,请参考以下文章

从android中动态创建的edittext获取价值?

Android,从edittext中获取文本[重复]

如何从 Android 中每个动态创建的 EditText 获取数据?

无法从警报对话框中的 EditText 视图中获取数据

从适配器类获取不同活动中的 EditText 值

如何从另一个活动中编辑和获取 editText 输入字段的更新?