没有输入或输入无效时如何防止我的应用崩溃

时间:2018-09-07 03:27:02

标签: java android xml

您好,我正在创建一个单位转换器应用,尝试自我学习如何使android应用如何在单击转换按钮时如何使我的应用显示消息而不是崩溃。如果输入为空或“,”这是我的代码。

我个人认为如果fromEditText中没有输入,则禁用该按钮。

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent">

     <Button
         android:id="@+id/button_convert"
         android:layout_width="231dp"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_centerHorizontal="true"
         android:layout_marginBottom="88dp"
         android:onClick="convert"
         android:text="Convert" />

     <TextView
         android:id="@+id/textView"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentTop="true"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="29dp"
         android:text="Unit 1"
         tools:layout_editor_absoluteX="16dp"
         tools:layout_editor_absoluteY="16dp" />

    <TextView
         android:id="@+id/textView2"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentTop="true"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="202dp"
         android:text="Unit 2"
         tools:layout_editor_absoluteX="16dp"
         tools:layout_editor_absoluteY="136dp" />

     <Spinner
         android:id="@+id/spinner_to"
         android:layout_width="368dp"
         android:layout_height="wrap_content"
         android:layout_alignParentStart="true"
         android:layout_alignParentLeft="true"
         android:layout_centerVertical="true"
         tools:layout_editor_absoluteX="8dp"
         tools:layout_editor_absoluteY="42dp"
         android:drawSelectorOnTop="true"/>

     <Spinner
         android:id="@+id/spinner_from"
         android:layout_width="368dp"
         android:layout_height="wrap_content"
         android:layout_alignParentStart="true"
         android:layout_alignParentLeft="true"
         android:layout_alignParentTop="true"
         android:layout_marginTop="69dp"
         tools:layout_editor_absoluteX="8dp"
         tools:layout_editor_absoluteY="163dp"
         android:drawSelectorOnTop="true"/>

     <EditText
         android:id="@+id/editText_to"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_centerHorizontal="true"
         android:layout_marginBottom="177dp"
         android:clickable="false"
         android:cursorVisible="false"
         android:ems="10"
         android:focusable="false"
         android:focusableInTouchMode="false"
         android:inputType="numberDecimal"
         tools:layout_editor_absoluteX="85dp"
         tools:layout_editor_absoluteY="223dp" />

     <EditText
         android:id="@+id/editText_from"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentTop="true"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="127dp"
         android:ems="10"
         android:inputType="numberDecimal"
         tools:layout_editor_absoluteX="85dp"
         tools:layout_editor_absoluteY="96dp" />
</RelativeLayout>

Java Converter类

package com.appcreator.isa.theunitconverterapp;

import android.widget.Toast;

import java.util.logging.LogRecord;

public class Converter
{
    public enum UnitsDistance
    {
        Inch,
        Centimetre,
        Foot,
        Yard,
        Metre,
        Mile,
        Kilometre,
        NauticalMile;

        private static LogRecord dlgAlert;

    // Helper method to convert text to one of the above constants
        public static UnitsDistance fromString(String text)
        {
             if (text != null)
             {
                  for (UnitsDistance UnitsDistance : UnitsDistance.values())
                  {
                      if (text.equalsIgnoreCase(UnitsDistance.toString()))
                      {
                          return UnitsDistance;
                      }
                  }
             }

             throw new IllegalArgumentException("Cannot find a value for " + text);
        }
    }

// What can I multiply by to get me from my fromUnitsDistance to my toUnitsDistance?
    private final double multiplier;
    public Converter(UnitsDistance from, UnitsDistance to)
    {
         double constant = 1;
        // Set the multiplier, else if fromUnitsDistance = toUnitsDistance, then it is 1
         switch (from)
         {
             case Inch:
                 if (to == UnitsDistance.Centimetre)
                 {
                     constant = 2.54;
                 } else if (to == UnitsDistance.Foot)
                 {
                     constant = 0.0833333;
                 } else if (to == UnitsDistance.Yard)
                 {
                     constant = 0.0277778;
                 } else if (to == UnitsDistance.Metre)
                 {
                     constant = 0.0254;
                 } else if (to == UnitsDistance.Mile)
                 {
                     constant = 1.5783e-5;
                 } else if (to == UnitsDistance.Kilometre)
                 {
                     constant = 2.54e-5;
                 } else if (to == UnitsDistance.NauticalMile)
                 {
                     constant = 1.3715e-5;
                 }
                 break;
             case Centimetre:
                 if (to == UnitsDistance.Inch)
                 {
                     constant = 0.393701;
                 } else if (to == UnitsDistance.Foot)
                 {
                     constant = 0.0328084;
                 } else if (to == UnitsDistance.Yard)
                 {
                     constant = 0.0109361;
                 } else if (to == UnitsDistance.Metre)
                 {
                     constant = 0.01;
                 } else if (to == UnitsDistance.Mile)
                 {
                     constant = 6.2137e-6;
                 } else if (to == UnitsDistance.Kilometre)
                 {
                     constant = 1e-5;
                 } else if (to == UnitsDistance.NauticalMile)
                 {
                     constant = 5.3996e-6;
                 }
                 break;
             case Foot:
                 if (to == UnitsDistance.Inch)
                 {
                     constant = 12;
                 } else if (to == UnitsDistance.Centimetre)
                 {
                     constant = 30.48;
                 } else if (to == UnitsDistance.Yard)
                 {
                     constant = 0.333333;
                 } else if (to == UnitsDistance.Metre)
                 {
                     constant = 0.3048;
                 } else if (to == UnitsDistance.Mile)
                 {
                     constant = 0.000189394;
                 } else if (to == UnitsDistance.Kilometre)
                 {
                     constant = 0.0003048;
                 } else if (to == UnitsDistance.NauticalMile )
                 {
                     constant = 0.000164579;
                 }
                 break;
             case Yard:
                 if (to == UnitsDistance.Inch)
                 {
                     constant = 36;
                 } else if (to == UnitsDistance.Centimetre)
                 {
                     constant = 91.44;
                 } else if (to == UnitsDistance.Foot)
                 {
                     constant = 3;
                 } else if (to == UnitsDistance.Metre)
                 {
                     constant = 0.9144;
                 } else if (to == UnitsDistance.Mile)
                 {
                     constant = 0.000568182;
                 } else if (to == UnitsDistance.Kilometre)
                 {
                     constant = 0.0009144;
                 } else if (to == UnitsDistance.NauticalMile )
                 {
                constant = 0.000493737;
            }
            break;
        case Metre:
            if (to == UnitsDistance.Inch)
            {
                constant = 39.3701;
            } else if (to == UnitsDistance.Centimetre)
            {
                constant = 100;
            } else if (to == UnitsDistance.Foot)
            {
                constant = 3.28084;
            } else if (to == UnitsDistance.Yard)
            {
                constant = 1.09361;
            } else if (to == UnitsDistance.Mile)
            {
                constant = 0.000621371;
            } else if (to == UnitsDistance.Kilometre)
            {
                constant = 0.001;
            } else if (to == UnitsDistance.NauticalMile)
            {
                constant = 0.000539957;
            }
            break;
        case Mile:
            if (to == UnitsDistance.Inch)
            {
                constant = 63360;
            } else if (to == UnitsDistance.Centimetre)
            {
                constant = 160934;
            } else if (to == UnitsDistance.Foot)
            {
                constant = 5280;
            } else if (to == UnitsDistance.Yard)
            {
                constant = 1760;
            } else if (to == UnitsDistance.Metre)
            {
                constant = 1609.34;
            } else if (to == UnitsDistance.Kilometre)
            {
                constant = 1.60934;
            } else if (to == UnitsDistance.NauticalMile)
            {
                constant = 1.1508;
            }
            break;
        case Kilometre:
            if (to == UnitsDistance.Inch)
            {
                constant = 39370.1;
            } else if (to == UnitsDistance.Centimetre)
            {
                constant = 100000;
            } else if (to == UnitsDistance.Foot)
            {
                constant = 3280.84;
            } else if (to == UnitsDistance.Yard)
            {
                constant = 1093.61;
            } else if (to == UnitsDistance.Metre)
            {
                constant = 1000;
            } else if (to == UnitsDistance.Mile)
            {
                constant = 0.621371;
            } else if (to == UnitsDistance.NauticalMile)
            {
                constant = 0.539957;
            }
            break;
        case NauticalMile:
            if (to == UnitsDistance.Inch)
            {
                constant = 72913.4;
            } else if (to == UnitsDistance.Centimetre)
            {
                constant = 185200;
            } else if (to == UnitsDistance.Foot)
            {
                constant = 6076.12;
            } else if (to == UnitsDistance.Yard)
            {
                constant = 2025.37;
            } else if (to == UnitsDistance.Metre)
            {
                constant = 1852;
            } else if (to == UnitsDistance.Mile)
            {
                constant = 1.15078;
            } else if (to == UnitsDistance.Kilometre)
            {
                constant = 1.852;
            }
            break;
    }

    multiplier = constant;
  }

  // Convert the UnitsDistance!
  public double convert(double input)
 {
    return input * multiplier;
 }

  }

Java Main Activity类

package com.appcreator.isa.theunitconverterapp;

 import android.content.Intent;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.text.Editable;
 import android.text.TextUtils;
 import android.text.TextWatcher;
 import android.view.View;
 import android.widget.ArrayAdapter;
 import android.widget.EditText;
 import android.widget.Spinner;
 import android.widget.Toast;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.OutputStreamWriter;
 import android.graphics.Color;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.view.Menu;

public class MainActivity extends AppCompatActivity
 {

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


     ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.unitsdistance, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    Spinner from = (Spinner)findViewById(R.id.spinner_from);
    Spinner to = (Spinner)findViewById(R.id.spinner_to);

    from.setAdapter(adapter);
    to.setAdapter(adapter);
    //setContentView(R.layout.activity_main);

}
public void convert(View view)
{
    Spinner fromSpinner, toSpinner;
    final EditText fromEditText, toEditText;

    fromSpinner = (Spinner) findViewById(R.id.spinner_from);
    toSpinner = (Spinner) findViewById(R.id.spinner_to);
    fromEditText = (EditText) findViewById(R.id.editText_from);
    toEditText = (EditText) findViewById(R.id.editText_to);

    // Get the string from the Spinners and number from the EditText
    String fromString = (String) fromSpinner.getSelectedItem();
    String toString = (String) toSpinner.getSelectedItem();
    double input = Double.valueOf(fromEditText.getText().toString());

    Button check =  (Button) findViewById(R.id.button_convert);




    // Convert the strings to something in our Unit enu,
    Converter.UnitsDistance fromUnit = Converter.UnitsDistance.fromString(fromString);
    Converter.UnitsDistance toUnit = Converter.UnitsDistance.fromString(toString);

    // Create a converter object and convert!
    Converter converter = new Converter(fromUnit, toUnit);

    double result = converter.convert(input);

    check.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            if (fromEditText.getText().toString().length() == 0 || fromEditText.getText().toString() == ".")
            {
                //Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
                Intent intent = getIntent();
                finish();
                startActivity(intent);
            }
        }
      });

     toEditText.setText(String.valueOf(result));
   }
  }

strings.xml

<resources>
<string name="app_name">The Unit Converter App</string>
<string-array name="unitsdistance">
    <item>Inch</item>
    <item>Centimetre</item>
    <item>Foot</item>
    <item>Yard</item>
    <item>Metre</item>
    <item>Mile</item>
    <item>Kilometre</item>
    <item>NauticalMile</item>
</string-array>
</resources>

每当我单击一个按钮时,如果EditText中没有任何内容或仅包含“”,应用程序就会停止运行。里面没有数字。

更新了主要活动

    package com.appcreator.isa.theunitconverterapp;



    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.Toast;
    import android.view.View.OnClickListener;
    import android.widget.Button;


    public class MainActivity extends AppCompatActivity
   {

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


    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.unitsdistance, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    Spinner from = (Spinner)findViewById(R.id.spinner_from);
    Spinner to = (Spinner)findViewById(R.id.spinner_to);

    from.setAdapter(adapter);
    to.setAdapter(adapter);

}
public void convert(View view)
{




    Button check =  (Button) findViewById(R.id.button_convert);




    check.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Spinner fromSpinner, toSpinner;
            EditText  toEditText;
            toEditText = (EditText) findViewById(R.id.editText_to);
            EditText fromEditText = (EditText) findViewById(R.id.editText_from);;


            fromSpinner = (Spinner) findViewById(R.id.spinner_from);
            toSpinner = (Spinner) findViewById(R.id.spinner_to);
            String fromString = (String) fromSpinner.getSelectedItem();
            String toString = (String) toSpinner.getSelectedItem();

            Converter.UnitsDistance fromUnit = Converter.UnitsDistance.fromString(fromString);
            Converter.UnitsDistance toUnit = Converter.UnitsDistance.fromString(toString);

            Converter converter = new Converter(fromUnit, toUnit);


            String str = fromEditText.getText().toString().trim();
            boolean valid = true;
            double val = 0;

            try {
                val = Double.parseDouble(str);
            }
            catch(NumberFormatException e)
            {
                valid = false;
            }

            if( valid )
            {
                // use the number
                if (fromEditText.getText().toString().trim().length() > 0 )
                {
                    double input = Double.valueOf(fromEditText.getText().toString().trim());
                    double result = converter.convert(input);
                    toEditText.setText(String.valueOf(result));
                }

            }
            else
                {
                // handle invalid entry
                    Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();

            }
        }
    });


     }
    }

1 个答案:

答案 0 :(得分:2)

如果要检查是否输入了有效数字,则可以解析该数字并捕获NumberFormatException以检测其是否有效。例如:

String str = fromEditText.getText().toString().trim();
boolean valid = true;
double val = 0;

try {
    val = Double.parseDouble(str);
}
catch(NumberFormatException e) {
    valid = false;
}

if( valid ) {
    // use the number
}
else {
    // handle invalid entry
}

除了空白和“。”以外,还有更多不可解析的组合。例如,“ ........”或空格,句号和逗号的任意数量的组合,用户可以出于某种原因决定输入。