Android EditText 的异常处理

Android Exception handling on EditText

我正在学习 Android 在线课程,但遇到了障碍。 当提交没有任何内容的 EditText(数字)字段时,我的应用程序崩溃。 据我所知,我已经尝试在代码中添加异常处理程序。坚果我仍然有同样的问题。我正在处理日志中显示的异常,如下所示。 InvocationTargetException Studio 中的 InvocationTargetException 条目标记为 Cannot resolve symbol InvocationTargetException。 我不确定这有什么问题或者是否相关。

代码:

package com.example.richardcurteis.higherorlower;

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.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import java.lang.reflect.Method;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    int randomNumber;
    EditText getUserInput;

    public int getRandomNumber() {
        Random randomGenerator = new Random();
        randomNumber = randomGenerator.nextInt(10) +1;
        return  randomNumber;
    }

    public void higherOrLower(View view) {
        String exceptionMessage = "";
        try {
            getUserInput = (EditText) findViewById(R.id.userInput);
        } catch (InvocationTargetException e) {
            exceptionMessage = "InvocationTargetException";
        } catch (NumberFormatException e) {
            exceptionMessage = "NumberFormatException";
        } catch (IllegalStateException e) {
            exceptionMessage = "IllegalStateException";
        }

        Toast.makeText(this, exceptionMessage, Toast.LENGTH_LONG).show();

        int userInteger = Integer.parseInt(getUserInput.getText().toString());

        String message = "";

        if (userInteger > randomNumber) {
            message = "Lower!";
            getUserInput.getText().clear();
        } else if (userInteger < randomNumber) {
            message = "Higher!";
            getUserInput.getText().clear();
        } else {
            message = "You win!";
            getUserInput.getText().clear();
            getRandomNumber();
        }

        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        randomNumber = getRandomNumber();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

错误:

12-28 16:36:23.985 5035-5035/com.example.richardcurteis.higherorlower E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                        Process: com.example.richardcurteis.higherorlower, PID: 5035
                                                                                        java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                                            at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:275)
                                                                                            at android.view.View.performClick(View.java:5198)
                                                                                            at android.view.View$PerformClick.run(View.java:21147)
                                                                                            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:5417)
                                                                                            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:270)
                                                                                            at android.view.View.performClick(View.java:5198) 
                                                                                            at android.view.View$PerformClick.run(View.java:21147) 
                                                                                            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:5417) 
                                                                                            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.richardcurteis.higherorlower.MainActivity.higherOrLower(MainActivity.java:40)
                                                                                            at java.lang.reflect.Method.invoke(Native Method) 
                                                                                            at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270) 
                                                                                            at android.view.View.performClick(View.java:5198) 
                                                                                            at android.view.View$PerformClick.run(View.java:21147) 
                                                                                            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:5417) 
                                                                                            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) 

查看错误日志显示您正在尝试将空白字符串解析为 int.

 Caused by: java.lang.NumberFormatException: Invalid int: ""

InvocationTargetException 只是动态调用中抛出的异常的包装器。

抛出异常是因为您试图捕获错误的代码片段。

使用此辅助方法将字符串转换为整数

public static Integer toInteger(final String str, final Integer defaultValue) {
            if (str == null) {
                return defaultValue;
            }
            try {
                return Integer.valueOf(str);
            } catch (NumberFormatException nfe) {
                return defaultValue;
            }
        }

像这样

Integer userInteger = toInteger(getUserInput.getText().toString(), null);

if (userInteger == null) {
  Toast.makeText(getApplicationContext(), "Invalid input", Toast.LENGTH_SHORT).show();
  return;
}

移动到 "try" 代码块的这行代码:

int userInteger = Integer.parseInt(getUserInput.getText().toString());