简体   繁体   English

Android表单验证-如何防止在按下按钮时空字段使我的应用程序崩溃?

[英]Android Form Validation - How do I prevent a null field from crashing my application on button press?

I have a form which lets the user add entries into a raffle. 我有一个表格,可以让用户将条目添加到抽奖中。 However if the user leaves one of these fields blank and presses the submit button the app crashes. 但是,如果用户将这些字段之一留空,然后按提交按钮,则应用程序将崩溃。 I tried to get around this by creating an if statement - if any of the fields are null, do nothing. 我试图通过创建if语句来解决此问题-如果任何字段为null,则什么也不做。 Else, run the intent. 否则,运行意图。 However this still does not fix my problem. 但是,这仍然不能解决我的问题。 Pressing the button still causes a crash. 按下按钮仍然会导致崩溃。

Here is my code: 这是我的代码:

 public void addEntrySubmitButtonClick(View view) {


        Intent addEntryIntent = getIntent();
        int currentRaffleID = addEntryIntent.getIntExtra("raffleIndexInList", 0);
        Raffle currentRaffle = Raffle.raffleArrayList.get(currentRaffleID);
        String newEntryForename = String.valueOf(addEntryForename.getText());
        String newEntrySurname = String.valueOf(addEntrySurname.getText());
        int newEntryTelephoneNo = Integer.parseInt(String.valueOf(addEntryTelephoneNo.getText()));
        int newEntryTicketCount = Integer.parseInt(String.valueOf(addEntryTicketCount.getText()));
        int newEntryRaffleId = currentRaffle.getId();

        if ((newEntryForename.equals(null)) || (newEntrySurname.equals(null)) || (String.valueOf(addEntryTelephoneNo).equals(null)) || (String.valueOf(addEntryTicketCount).equals(null))){
        Intent failIntent = new Intent();
        } else {
            Entry newEntry = new Entry(newEntryForename, newEntrySurname, newEntryTelephoneNo, newEntryTicketCount, newEntryRaffleId);


            // Get the list of raffles
            for(Raffle currentEntryRaffle : Raffle.raffleArrayList) {
                if((currentEntryRaffle.getId() == newEntryRaffleId) && ((currentEntryRaffle.getEntryArrayList().size()) < (currentEntryRaffle.getMaxTickets()))) {
                    int counter=0;
                    do {
                        currentEntryRaffle.getEntryArrayList().add(newEntry);
                        counter++;
                    } while(counter < newEntryTicketCount);
                }
            }

            Intent returnIntent = new Intent();
            setResult(RESULT_CANCELED, returnIntent);
            finish();
        }

Here is the logcat: 这是logcat:

10-24 10:48:42.599  19481-19481/com.example.rafflemanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View$1.onClick(View.java:3628)
            at android.view.View.performClick(View.java:4128)
            at android.view.View$PerformClick.run(View.java:17142)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:4787)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at android.view.View$1.onClick(View.java:3623)
            at android.view.View.performClick(View.java:4128)
            at android.view.View$PerformClick.run(View.java:17142)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:4787)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NumberFormatException: Invalid int: ""
            at java.lang.Integer.invalidInt(Integer.java:138)
            at java.lang.Integer.parseInt(Integer.java:359)
            at java.lang.Integer.parseInt(Integer.java:332)
            at com.example.rafflemanager.AddEntry.addEntrySubmitButtonClick(AddEntry.java:48)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at android.view.View$1.onClick(View.java:3623)
            at android.view.View.performClick(View.java:4128)
            at android.view.View$PerformClick.run(View.java:17142)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:4787)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
            at dalvik.system.NativeStart.main(Native Method)
newEntryForename.equals(null)

The above expression will either evaluate to false or throw a NullPointerException . 上面的表达式将计算为false或抛出NullPointerException It is impossible to call a method on a null reference. 不能在null引用上调用方法。

String.valueOf(addEntryTelephoneNo).equals(null)

The above expression will always evaluate to false . 上面的表达式将始终为false From String.valueOf javadoc: String.valueOf javadoc:

Returns: if the argument is null, then a string equal to "null"; 返回:如果参数为null,则等于“ null”的字符串;否则为false。 otherwise, the value of obj.toString() is returned. 否则,返回obj.toString()的值。

What you want instead is simply 相反,您想要的只是

addEntryTelephoneNo == null

and similar for other cases. 与其他情况类似。

Furthermore note that you are trying to parse the value before you have null-checked it: 此外请注意,在对值进行空检查之前 ,您尝试解析该值:

int newEntryTelephoneNo = Integer.parseInt(String.valueOf(addEntryTelephoneNo.getText()));

Move that code to after the null check. 将代码移到null检查之后。

I'm writing this from a smartphone so I won't include any codesamples with this answer. 我是从智能手机上编写的,因此我不会在此答案中包含任何代码样本。

Anyway... First of all remove all String.valueOf() calls - they are redundant. 无论如何...首先删除所有String.valueOf()调用-它们是多余的。 Second, to see if a value is null, check for value == null, not value.equals(null). 其次,要查看值是否为null,请检查value == null,而不是value.equals(null)。 If value is null, it doesn't have the method equals(), and will thus lead to a NullReferenceException. 如果value为null,则没有方法equals(),因此将导致NullReferenceException。

Also, don't call Integer.parseInt(value) before you have made sure that value isn't null. 另外,在确保值不为null之前,请勿调用Integer.parseInt(value)。

Disabling the send button when the EditText is empty when using imeOption= actionSend 使用imeOption = actionSend时,当EditText为空时,禁用发送按钮

message.addTextChangedListener(new TextWatcher() {

public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}

public void afterTextChanged(Editable s) {
    if (s == null || s.length() == 0) {
       send.setEnabled(false);
       message.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
    }
    else {
      send.setEnabled(true);
      message.setImeOptions( /* whatever you previously had */ );
    }

} }

To check if a string is empty (null or length 0) use TextUtils.isEmpty() . 要检查字符串是否为空(空或长度为0),请使用TextUtils.isEmpty() Here's an example: 这是一个例子:

int newEntryTelephoneNo;
if (TextUtils.isEmpty(addEntryTelephoneNo.getText())) {
    newEntryTelephoneNo = 0;
} else {
    newEntryTelephoneNo = Integer.parseInt(addEntryTelephoneNo.getText());
}

The problem in your logcat is this : 您的logcat中的问题是这样的:

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

Without line numbers, I deduct that the problem comes from one line like this one : 没有行号,我推断问题出在这样的一行:

int newEntryTelephoneNo = Integer.parseInt(String.valueOf(addEntryTelephoneNo.getText()));

Reading the following docs give us a hint : http://developer.android.com/reference/java/lang/Integer.html#parseInt(java.lang.String) 阅读以下文档会给我们一个提示: http : //developer.android.com/reference/java/lang/Integer.html#parseInt(java.lang.String)

Throws 抛出

NumberFormatException if string cannot be parsed as an integer value. NumberFormatException如果无法将字符串解析为整数值。

The Integer.parseInt() seems not able to parse an empty String to an int (and it's normal, because a int can't be null ). Integer.parseInt()似乎无法将空String解析为int (这很正常,因为int不能为null )。

So I think you should make something like that : 所以我认为你应该做这样的事情:

int newEntryTelephoneNo = 0;
if (!TextUtils.isEmpty(addEntryTelephoneNo.getText())) {
    newEntryTelephoneNo = Integer.parseInt(addEntryTelephoneNo.getText());
}

Not about the main question 与主要问题无关

Also, as other answers and comment said, you have to use this to check the "nullity" of an object : 另外,正如其他答案和评论所说,您必须使用它来检查对象的“空值”:

myObject == null

instead of 代替

myObject.equals(null)

because you can't even call equals() or any other methods on a null instance. 因为您甚至无法在null实例上调用equals()或任何其他方法。

The logcat clearly shows the exception occurs when the call to Integer.parseInt throws a NumberFormatException . logcat清楚地显示了对Integer.parseInt的调用引发NumberFormatException时发生的异常。 This occurs when the string cannot be converted to an int. 当字符串无法转换为int时,就会发生这种情况。 If you check the line numbers you will see exactly which conversion generated the exception. 如果检查行号,您将确切看到哪个转换产生了异常。

Depending on your needs you probably want to both test for acceptable invalid entries like empty string and catch NumberFormatException due to invalid input so that you can inform the user of the invalid entry. 根据您的需要,您可能既要测试可接受的无效条目(如空字符串), NumberFormatException由于无效输入而引起的NumberFormatException异常,以便您可以将无效条目通知用户。

Here is the code you need: 这是您需要的代码:

public void addEntrySubmitButtonClick(View view) {


    Intent addEntryIntent = getIntent();
    int currentRaffleID = addEntryIntent.getIntExtra("raffleIndexInList", 0);
    Raffle currentRaffle = Raffle.raffleArrayList.get(currentRaffleID);
    String newEntryForename = String.valueOf(addEntryForename.getText());
    String newEntrySurname = String.valueOf(addEntrySurname.getText());
    int newEntryTelephoneNo = Integer.parseInt(String.valueOf(addEntryTelephoneNo.getText()));
    int newEntryTicketCount = Integer.parseInt(String.valueOf(addEntryTicketCount.getText()));
    int newEntryRaffleId = currentRaffle.getId();

    if (newEntryForename==null || newEntrySurname == null || String.valueOf(addEntryTelephoneNo) == null || String.valueOf(addEntryTicketCount) == null){
    Intent failIntent = new Intent();
    } else {
        Entry newEntry = new Entry(newEntryForename, newEntrySurname, newEntryTelephoneNo, newEntryTicketCount, newEntryRaffleId);


        // Get the list of raffles
        for(Raffle currentEntryRaffle : Raffle.raffleArrayList) {
            if((currentEntryRaffle.getId() == newEntryRaffleId) && ((currentEntryRaffle.getEntryArrayList().size()) < (currentEntryRaffle.getMaxTickets()))) {
                int counter=0;
                do {
                    currentEntryRaffle.getEntryArrayList().add(newEntry);
                    counter++;
                } while(counter < newEntryTicketCount);
            }
        }

        Intent returnIntent = new Intent();
        setResult(RESULT_CANCELED, returnIntent);
        finish();
    }

You have to replace .equals(null) with == null since calling a method on a null pointer will crash your app. 您必须用== null替换.equals(null),因为在空指针上调用方法将使您的应用程序崩溃。

暂无
暂无

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

相关问题 当单击按钮从网络加载图像时,如何防止表单冻结? - How do I prevent my form from freezing when it is loading an image from the web at the click of a button? 我需要通过按下我的统一应用程序中的按钮来加载 android 相机应用程序 - I need to load android camera app by press on button from my unity application Android Studio - 按下按钮后如何让我的 RecyclerView 包含更多项目? - Android Studio - How do I make my RecyclerView contain more items after a button press? 当我从我的应用程序中按下后退按钮时,Countdowntimer 如何继续在后台运行? - How Countdowntimer continue Running in the background when i press back button from my application? 如何通过按按钮从android程序堆栈中删除除第一项以外的所有项? - How do I remove all items but the first from the android program stack by button press? 如何防止我的android中的“提交”按钮在多次单击时给我多个分数? - How do I prevent my submit button in android from giving me multiple scores when clicked multiple times? 如何修复AdMob导致我的Android应用崩溃? - How do I fix AdMob crashing my Android app? 如何从Android应用程序中的按钮获取文本 - How do I get the text from a button in an Android application 如何在Android中按下按钮拨打号码? - How can I call a number from button press in Android? DisplayMessageActivity后退按钮不断崩溃我的Android应用程序 - DisplayMessageActivity back button keeps crashing my android application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM