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

时间:2014-10-24 10:11:11

标签: java android arraylist android-edittext android-button

我有一个表单,允许用户将条目添加到抽奖中。但是,如果用户将其中一个字段留空并按下提交按钮,则应用程序崩溃。我尝试通过创建if语句来解决这个问题 - 如果任何字段为null,则不执行任何操作。否则,运行意图。但是,这仍然无法解决我的问题。按下按钮仍然会导致崩溃。

这是我的代码:

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

这是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)

7 个答案:

答案 0 :(得分:1)

newEntryForename.equals(null)

上述表达式将评估为false或抛出NullPointerException。在null引用上调用方法是不可能的。

String.valueOf(addEntryTelephoneNo).equals(null)

上述表达式将始终评估为false。来自String.valueOf javadoc:

  

返回:如果参数为null,则字符串等于“null”;否则,返回obj.toString()的值。

你想要的只是

addEntryTelephoneNo == null

和其他情况类似。

此外请注意,您尝试在之前解析值,并对其进行了空检查:

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

在空检查之后将该代码移动。

答案 1 :(得分:0)

我是用智能手机写的,所以我不会在这个答案中包含任何代码示例。

无论如何......首先删除所有String.valueOf()调用 - 它们是多余的。其次,要查看值是否为null,请检查value == null,而不是value.equals(null)。如果value为null,则它没有equals()方法,因此会导致NullReferenceException。

此外,在确保该值不为null之前,请不要调用Integer.parseInt(value)。

答案 2 :(得分:0)

Disabling the send button when the EditText is empty when using imeOption= actionSend

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

}

答案 3 :(得分:0)

要检查字符串是否为空(null或长度为0),请使用TextUtils.isEmpty()。这是一个例子:

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

答案 4 :(得分:0)

logcat中的问题是:

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

没有行号,我推断问题来自这一行:

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

阅读以下文档会给我们一个提示:http://developer.android.com/reference/java/lang/Integer.html#parseInt(java.lang.String)

  

<强>抛出

     

如果无法将字符串解析为整数值,则为NumberFormatException。

Integer.parseInt()似乎无法将空字符串解析为int(这是正常的,因为int无法null })。

所以我认为你应该做出类似的事情:

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

不是主要问题

另外,正如其他答案和评论所说,你必须用它来检查&#34;无效&#34;一个对象:

myObject == null

而不是

myObject.equals(null)

因为您甚至无法在equals()个实例上调用null或任何其他方法。

答案 5 :(得分:0)

logcat清楚地显示了对Integer.parseInt的调用引发NumberFormatException时发生的异常。当字符串无法转换为int时会发生这种情况。如果检查行号,您将确切地看到生成异常的转换。

根据您的需要,您可能希望同时测试可接受的无效条目,例如空字符串,并且由于输入无效而捕获NumberFormatException,以便您可以通知用户无效条目。

答案 6 :(得分:0)

以下是您需要的代码:

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

您必须使用== null替换.equals(null),因为在空指针上调用方法会使您的应用程序崩溃。