当editText为空时,应用程序在按钮单击时崩溃

时间:2016-09-14 04:59:33

标签: android

我正在创建一个杂货店的单个屏幕应用程序,但在检查总价格时,如果用户没有输入任何内容,它应默认等于0但我的应用程序崩溃 下面是相同的代码

Activity.xml

    <?xml version="1.0" encoding="utf-8"?>



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.ashis.singlescreenapp.MainActivity">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/headline"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textView2" />
    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@mipmap/grocery_logo"
        android:id="@+id/imageView"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/qty_heading"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textView_qty"
        android:layout_below="@+id/imageView"
        android:layout_alignLeft="@+id/imageView"
        android:layout_alignStart="@+id/imageView" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView_qty"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/linearLayout">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="10"
            android:id="@+id/editText_apples"
            android:layout_weight="1"
            android:hint="Apples ($2 per piece)" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="10"
            android:id="@+id/editText_orange"
            android:layout_weight="1"
            android:hint="Orange($3 per piece)" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/linearLayout2">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="10"
            android:id="@+id/editText_mango"
            android:layout_weight="1"
            android:hint="Mango($4 per piece)" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="10"
            android:id="@+id/editText_banana"
            android:layout_weight="1"
            android:hint="Banana($1 per piece)" />
    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_confirm"
        android:text="@string/btn_confirm"
        android:onClick="onbuttonClicked"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textView_result"
        android:minWidth="300dp"
        android:layout_below="@+id/linearLayout2"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check"
        android:id="@+id/button"
        android:layout_above="@+id/button_confirm"
        android:layout_centerHorizontal="true"
        android:onClick="checkPrice" />

</RelativeLayout>

MainActivity.java

package com.example.ashis.singlescreenapp;

import android.content.Intent;
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 android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText editText_apples,editText_orange,editText_mango,editText_banana;
    int apples,orange,mango,banana;
    TextView textView_result;

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



    }

    public void checkPrice(View view)
    {
        editText_apples=(EditText) findViewById(R.id.editText_apples);
        editText_orange=(EditText) findViewById(R.id.editText_orange);
        editText_banana=(EditText) findViewById(R.id.editText_banana);
        editText_mango=(EditText) findViewById(R.id.editText_mango);
        textView_result=(TextView) findViewById(R.id.textView_result);
        apples=Integer.parseInt(editText_apples.getText().toString());
        orange=Integer.parseInt(editText_orange.getText().toString());
        mango=Integer.parseInt(editText_mango.getText().toString());
        banana=Integer.parseInt(editText_banana.getText().toString());
        if (editText_apples.getText().toString().equals(""))
        {
            apples=0;
        }
        else if (editText_banana.getText().toString().equals(""))
        {
            banana=0;
        }
        else if (editText_orange.getText().toString().equals(""))
        {
            orange=0;
        }
        else if (editText_mango.getText().toString().equals(""))
        {
            mango=0;
        }
        else {
            int result = getPrice(apples, orange, mango, banana);
            textView_result.setText(String.valueOf(result));
        }
    }
    private int getPrice(int apples, int orange, int mango, int banana) {

        int result= (apples*2) + (orange*3) + (mango*4) + (banana);

    return result;
    }
/*
    public void onbuttonClicked(View view)
    {

        String email_body = "Dear Grocery Store, \n" + "Send all the following  ";
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_EMAIL,"ashish.choudhary@groceryStore.com");
        intent.putExtra(Intent.EXTRA_SUBJECT," Send All these Product");
        intent.putExtra(Intent.EXTRA_TEXT,"");

    }
*/
}

当我点击确认按钮

时,这是logCat
FATAL EXCEPTION: main
                                                                                   Process: com.example.ashis.singlescreenapp, PID: 22748
                                                                                   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:5226)
                                                                                       at android.view.View$PerformClick.run(View.java:21350)
                                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:5571)
                                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                    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:5226) 
                                                                                       at android.view.View$PerformClick.run(View.java:21350) 
                                                                                       at android.os.Handler.handleCallback(Handler.java:739) 
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                                       at android.os.Looper.loop(Looper.java:148) 
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:5571) 
                                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
                                                                                    Caused by: java.lang.NumberFormatException: Invalid int: ""
                                                                                       at java.lang.Integer.invalidInt(Integer.java:138)
                                                                                       at java.lang.Integer.parseInt(Integer.java:358)
                                                                                       at java.lang.Integer.parseInt(Integer.java:334)
                                                                                       at com.example.ashis.singlescreenapp.MainActivity.checkPrice(MainActivity.java:36)
                                                                                       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:5226) 
                                                                                       at android.view.View$PerformClick.run(View.java:21350) 
                                                                                       at android.os.Handler.handleCallback(Handler.java:739) 
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                                       at android.os.Looper.loop(Looper.java:148) 
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:5571) 
                                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

6 个答案:

答案 0 :(得分:2)

问题是你正在尝试格式化一个空字符串。请检查

if(!edittext.getText().toString().equals("")) {
   apples = Integer.parseInt(edittext.getText().toString()); 
} else {
    apples = 0;
}

或者您可以使用简短形式:

apples = edittext.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());

答案 1 :(得分:0)

在检查空字符串之前,您正在调用parseInt。空字符串上的parseInt将抛出异常。在任何情况下,您都应该使用try catch围绕parseInt

答案 2 :(得分:0)

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

        editText_apples=(EditText) findViewById(R.id.editText_apples);
        editText_orange=(EditText) findViewById(R.id.editText_orange);
        editText_banana=(EditText) findViewById(R.id.editText_banana);
        editText_mango=(EditText) findViewById(R.id.editText_mango);
        textView_result=(TextView) findViewById(R.id.textView_result);
        checkPrice();

    }

    public void checkPrice()
    {
        apples = edittext_apples.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
        orange=editText_orange..getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
        mango=editText_mango..getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
        banana=editText_banana.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
        ...............
    }

答案 3 :(得分:0)

您可以调试代码,您会看到 - 您正在尝试在检查文本之前解析int。 每个编辑文本都需要这样的东西:

if (editText_apples.getText().toString().equals("")) {
    apples=0;
} else {
    apples=Integer.parseInt(editText_apples.getText().toString());
}

或短变种:

apples = editText_apples.getText().toString().isEmpty() ? 0 
: Integer.parseInt(editText_apples.getText().toString());

可以肯定的是,在编辑文本中只有数字,您可以为编辑文本添加inputType:

<EditText
...
android:inputType="number"/>

答案 4 :(得分:0)

尝试从空字符串解析整数时遇到一些问题。尝试替换这段代码:

apples=Integer.parseInt(editText_apples.getText().toString());
        orange=Integer.parseInt(editText_orange.getText().toString());
        mango=Integer.parseInt(editText_mango.getText().toString());
        banana=Integer.parseInt(editText_banana.getText().toString());
        if (editText_apples.getText().toString().equals(""))
        {
            apples=0;
        }
        else if (editText_banana.getText().toString().equals(""))
        {
            banana=0;
        }
        else if (editText_orange.getText().toString().equals(""))
        {
            orange=0;
        }
        else if (editText_mango.getText().toString().equals(""))
        {
            mango=0;
        }
        else {
            int result = getPrice(apples, orange, mango, banana);
            textView_result.setText(String.valueOf(result));
        }

用这个:

String txt1 = editText_apples.getText().toString();
apples=Integer.parseInt("".equals(txt1.trim()) ? "0" : txt1);

String txt2 = editText_orange.getText().toString();
orange=Integer.parseInt("".equals(txt2.trim()) ? "0" : txt2);

String txt3 = editText_mango.getText().toString();
mango=Integer.parseInt("".equals(txt3.trim()) ? "0" : txt3);

String txt4 = editText_banana.getText().toString();
banana=Integer.parseInt("".equals(txt4.trim()) ? "0" : txt4);

 int result = getPrice(apples, orange, mango, banana);
         textView_result.setText(String.valueOf(result));

答案 5 :(得分:0)

设置内容时初始化视图

public class MainActivity extends AppCompatActivity {

                EditText editText_apples,editText_orange,editText_mango,editText_banana;
                int apples,orange,mango,banana;
                TextView textView_result;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    editText_apples=(EditText) findViewById(R.id.editText_apples);
                    editText_orange=(EditText) findViewById(R.id.editText_orange);
                    editText_banana=(EditText) findViewById(R.id.editText_banana);
                    editText_mango=(EditText) findViewById(R.id.editText_mango);
                    textView_result=(TextView) findViewById(R.id.textView_result);


                }

                public void checkPrice(View view)
                {

                  if(TextUtils.isDigitOnly(editText_apples.getText().toString()){ 
                      apples=Integer.parseInt(editText_apples.getText().toString());
                   }else{
                        apples=0;
                   }
                   if(TextUtils.isDigitOnly(editText_orange.getText().toString()){ 
                      orange=Integer.parseInt(editText_orange.getText().toString());
                   }else{
                         orange=0;
                   }
                   if(TextUtils.isDigitOnly(editText_mango.getText().toString()){

                      mango=Integer.parseInt(editText_mango.getText().toString());
                   }else{
                         mango=0;
                   }
                    if(TextUtils.isDigitOnly(editText_banana.getText().toString()){
                       banana=Integer.parseInt(editText_banana.getText().toString());
                    }else{
                          banana=0;
                    }

                    int result = getPrice(apples, orange, mango, banana);
                    textView_result.setText(String.valueOf(result));

                }
                private int getPrice(int apples, int orange, int mango, int banana) {

                    int result= (apples*2) + (orange*3) + (mango*4) + (banana);

                return result;
                }
            }

在按钮点击时你的代码中的视图被初始化然后你将能够使用它们并且编辑文本中的值为空,因此将它们转换为整数会生成空指针异常。