java - 无法执行 android :onClick 的方法

标签 java android xml android-studio

我正在制作一个测验应用程序,并且使用一个 EditText,当我不在其中输入任何内容并SubmitButton 时,我收到此错误:

FATAL EXCEPTION: main
Process: com.example.andriod.quiz, PID: 12960
java.lang.IllegalStateException: Could not execute method for android:onClick 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19761)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5264)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4756) 
at android.view.View$PerformClick.run(View.java:19761) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5264) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695) 
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:284)
at android.widget.TextView.setText(TextView.java:4176)
at com.example.andriod.quiz.MainActivity.submitAnswer(MainActivity.java:65)
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4756) 
at android.view.View$PerformClick.run(View.java:19761) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5264) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)

这是我的java代码:

package com.example.andriod.quiz;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This app displays Millionaire Quiz
 */
public class MainActivity extends AppCompatActivity {

private String name;
private int correctAnswers;

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

/**
 * This method is called when the Ok button is clicked. it's displays personalized greetings.
 *
 * @param view
 */
public void greetings(View view) {
    EditText nameField = (EditText) findViewById(R.id.customer_name);
    name = nameField.getText().toString();
    TextView greetings = (TextView) findViewById(R.id.greetings);
    greetings.setText("Hello " + name + ". Scroll down if you are ready.");

    InputMethodManager inputManager = (InputMethodManager)
            getSystemService(Context.INPUT_METHOD_SERVICE);

    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);

    LinearLayout questionsLayout = (LinearLayout) findViewById(R.id.questions_layout);
    questionsLayout.setVisibility(View.VISIBLE);
}


/**
 * Checks correct answers, and displays a toast with congratulations and amount of correctly answered questions.
 *
 * @param view
 */
public void submitAnswer(View view) {
    correctAnswers = 0;
    RadioButton firstQuestion = (RadioButton) findViewById(R.id.first_correct);
    if (firstQuestion.isChecked()) {
        correctAnswers++;
    }

    EditText secondQuestion = (EditText) findViewById(R.id.second_question);

            int answer = Integer.parseInt(secondQuestion.getText().toString());


    if (answer == 27) {
        correctAnswers++;
    }

    CheckBox checkBoxA = (CheckBox) findViewById(R.id.answer_a);
    CheckBox checkBoxB = (CheckBox) findViewById(R.id.answer_b);
    CheckBox checkBoxC = (CheckBox) findViewById(R.id.answer_c);
    CheckBox checkBoxD = (CheckBox) findViewById(R.id.answer_d);
    if (!checkBoxA.isChecked() && checkBoxB.isChecked() && checkBoxC.isChecked() && !checkBoxD.isChecked()) {
        correctAnswers++;
    }

    RadioButton fourthQuestion = (RadioButton) findViewById(R.id.fourth_correct);
    if (fourthQuestion.isChecked()) {
        correctAnswers++;
    }

    RadioButton fifthQuestion = (RadioButton) findViewById(R.id.fifth_correct);
    if (fifthQuestion.isChecked()) {
        correctAnswers++;
    }

    String correctlyAnswered;
    switch (correctAnswers) {
        case 5:
            correctlyAnswered = "Congratulation " + name + " you answer correctly to every question! You won 1 million! ";
            break;
        case 4:
            correctlyAnswered = "Congratulation " + name + "  you answer correctly to 4 questions! You won 750 thousands! You should try one more time!";
            break;
        case 3:
            correctlyAnswered = "Congratulation " + name + "  you answer correctly to 3 questions! You won 500 thousands! You should try one more time!";
            break;
        case 2:
            correctlyAnswered = "Congratulation " + name + "  you answer correctly to 3 questions! You won 250 thousands! You should try one more time!";
            break;
        case 1:
            correctlyAnswered = "Congratulation " + name + "  you answer correctly to 1 question! You won 100 thousands! You should try one more time!";
            break;
        default:
            correctlyAnswered = "You didn't answer correctly  to any question :( \nYou should try one more time!";
    }
    Toast toast = Toast.makeText(this, correctlyAnswered, Toast.LENGTH_LONG);
    toast.show();
}
}

这是 xml 文件:

        <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/second_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#6158AC"
android:orientation="vertical"
tools:context="com.example.andriod.quiz.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="16dp"
        android:text="Welcome in Millionaire Game! \nAre you ready to play for a million?"
        android:textSize="24sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/customer_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="Name"
            android:inputType="textCapWords" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="greetings"
            android:text="Ok"
            android:textAllCaps="true" />
    </LinearLayout>

    <TextView
        android:id="@+id/greetings"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="16dp"
        android:paddingTop="16dp"
        android:textSize="24sp" />

    <LinearLayout
        android:id="@+id/questions_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="visible">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="First question: \nHow many parts has Harry Potter series?" />

        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RadioButton
                android:id="@+id/first_correct"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Seven" /><!--correct-->
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Eight" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Six" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Three" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Second question: \nOwen thinks of a number, adds 13, and then divides the result by 5.  The answer is 8. Find the number Owen thinks of." />

        <EditText
            android:id="@+id/second_question"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:inputType="number"
            android:hint="Write here your answer." />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Third question: \nWhat is a value of absolute zero?" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <CheckBox
                android:id="@+id/answer_a"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="-189°C" />

            <CheckBox
                android:id="@+id/answer_b"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="-271,15°C" /><!--correct-->
            <CheckBox
                android:id="@+id/answer_c"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="0K" /><!--correct-->
            <CheckBox
                android:id="@+id/answer_d"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="100K" />
        </LinearLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fourth question: \nWhat is the main component in glass?" />

        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RadioButton
                android:id="@+id/fourth_correct"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Sand" /> <!--correct-->
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Iron" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Coal" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Water" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fifth question: \nWhich is the largest species of the tiger?" />

        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Chinese tiger" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Bengali tiger" />

            <RadioButton
                android:id="@+id/fifth_correct"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Siberian tiger" /><!--correct-->
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Indo-Chinese tiger" />
        </RadioGroup>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="submitAnswer"
            android:text="Submit answers"
            android:textAllCaps="true" />

    </LinearLayout>
</LinearLayout>

有谁知道为什么会出现这个错误吗? 我对我犯的每一个错误感到抱歉,这是我的第一个问题;)

最佳答案

这里失败了:

int answer = Integer.parseInt(secondQuestion.getText().toString());

这里必须有一个非空字段,而且它应该是一个数字。

您可以简单地检查:

int answer = 0;
EditText secondQuestion = (EditText) findViewById(R.id.second_question);

if(secondQuestion.getText().toString().equals("")) { 
   //Handle invalid input
} else {
   answer = Integer.parseInt(secondQuestion.getText().toString());
}

只需对无效输入进行一些验证,就可以轻松处理。

关于java - 无法执行 android :onClick 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45112459/

相关文章:

java - 将自由图表插入面板

java - SSL fatal error - 握手失败 (40)

java - android 打开消息从 ListView 到编辑文本

javascript - 如何在 android 的 Webview 中使用 Javascript 加载 HTML 代码

XML 验证错误

java - Popup设置为wrap_content后如何获取其高度?

java - 如何在 Yaml 日期字符串中设置时区?

java - 避免在 android 中使用断言

c# - 使用 linq to xml 获取特定值

.net - 全局属性 'http://www.w3.org/XML/1998/namespace:lang' 已经声明