简体   繁体   English

Android对EditText的异常处理

[英]Android Exception handling on EditText

I am going through an Android course online and have hit a stumbling block. 我正在在线上学习Android课程,遇到了绊脚石。 When an EditText (Number) field is submitted without any content, my app crashes. 提交了没有任何内容的EditText(数字)字段时,我的应用程序崩溃了。 I have tried adding exception handlers to the code, to my understanding. 据我了解,我尝试将异常处理程序添加到代码中。 Nut I still have the same problem. 坚果我仍然有同样的问题。 I am handling the exceptions that show up in my logs, shown below. 我正在处理日志中显示的异常,如下所示。 The InvocationTargetException entry flags in Android Studio as Cannot resolve symbol InvocationTargetException . Android Studio中的InvocationTargetException条目标志为Cannot resolve symbol InvocationTargetException I'm not sure what the problem is with that or if it might be related. 我不知道这是什么问题,或者可能是相关的。

Code: 码:

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);
    }
}

Errors: 错误:

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) 

Use this helper method to convert string to integer 使用此辅助方法将字符串转换为整数

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;
            }
        }

Something like this 像这样

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());

Looking through the error log it shows you're trying to parse a blank string to an int . 查看错误日志,它表明您正在尝试将空白字符串解析为int

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

InvocationTargetException is just a wrapper for an exception that's thrown within a dynamic invocation. InvocationTargetException只是动态调用中引发的异常的包装。

The exceptions are thrown because you're try catching around the wrong snippet of code. 引发异常是因为您尝试捕获错误的代码段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM