Я пытаюсь понять, почему мое приложение не работает

Ни за что не могу понять, что я делаю не так. Когда я нажимаю кнопку, приложение вылетает. Если бы кто-то мог помочь с этой проблемой, вы были бы великолепны. Мне нужно, чтобы это прекратилось, чтобы я мог проверить функциональность. Хорошо, если вы видите что-то еще не так с моим кодом или видите лучший способ сделать, пожалуйста, не стесняйтесь поправлять меня. Конструктивная обратная связь всегда приветствуется.

Это все функции, которые он должен иметь. https://thewikihow.com/video_qAXK2RxIh_s

Вот мой код:

public class MainActivity extends AppCompatActivity {

    RadioGroup radioGroup;
    RadioButton radioButton;
    TextView selected_button;
    TextView problem;
    TextView correct_answer;
    EditText user_answer;
    TextView support;

    int counter = 0;

    int high = 0;
    int low = 99;
    int count= 0;
    public int randGen(int low, int high) {
        return (int) Math.round(Math.random() * (high - low)) + low;
    }

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

        radioGroup = findViewById(R.id.radioGroup);

        selected_button = findViewById(R.id.selection);

        problem = findViewById(R.id.equation);

        user_answer = findViewById(R.id.solution);

        correct_answer = findViewById(R.id.answer_check);

        support = findViewById(R.id.encouragement);

        final Button buttonChecked = findViewById(R.id.button_check);
        Button buttonProblem = findViewById(R.id.button_problem);

        buttonProblem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //boolean checked = ((RadioButton) view).isChecked();

                //Timer
                new CountDownTimer(30000,100){
                    public void onTick(long millisUnitilFinished){
                        support.setText(String.valueOf(counter));
                    }

                    public void onFinish(){

                    }
                }.start();

                int radioId = radioGroup.getCheckedRadioButtonId();

                radioButton = findViewById(radioId);

                user_answer.setText(" ");

                //Addition method
                if (radioId == R.id.add){

                    int num1;
                    int num2;
                    int sum;

                    num1 = randGen(0,99);
                    num2 = randGen(0,99);

                    problem.setText(num1 + '+' + num2 + '=');

                    sum = num1 + num2;

                    correct_answer.setText(sum);

                    support.setText(" ");

                }
                //Subtraction method
                if (radioId == R.id.sub){

                    int num1;
                    int num2;
                    int diff;

                    num1 = randGen(0,99);
                    num2 = randGen(0,99);

                    problem.setText(num1 + '+' + num2 + '=');

                    diff = num1 - num2;

                    correct_answer.setText(diff);

                    support.setText(" ");


                }
                //Product method
                if (radioId == R.id.prod){

                    int num1;
                    int num2;
                    int product;

                    num1 = randGen(0,99);
                    num2 = randGen(0,99);

                    problem.setText(num1 + '+' + num2 + '=');

                    product = num1 * num2;

                    correct_answer.setText(product);

                    support.setText(" ");


                }
                //Division Method
                //Should only give problems whose remainder is zero.
                if (radioId == R.id.div){

                    int num1;
                    int num2;
                    int division;

                    num1 = randGen(0,99);
                    num2 = randGen(0,99);

                    problem.setText(num1 + '+' + num2 + '=');

                    division = num1 / num2;

                    correct_answer.setText(division);

                    support.setText(" ");

                }

            }
        });

        buttonChecked.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //correct answer
                if (user_answer == (EditText) correct_answer){
                    support.setText("Keep up the good work!");
                    buttonChecked.setEnabled(false);
                }
                //incorrect answer number 2
                else if (count == 1){
                    buttonChecked.setEnabled(false);
                    support.setText("This is the correct answer" + correct_answer + "You suck!");
                    count--;
                }
                //incorrect answer number 1
                else if (user_answer != correct_answer){
                    support.setText("I guess you can try one more time.");
                    count++;
                }
                //If no answer is typed but button is pressed.
                if (user_answer.length()==0){
                    support.setText("ANSWER THE QUESTION!!");

                }


            }
        });

    }
    //Message that lets user know what operation they have selected
    public void checkButton(View v){
        int radioId = radioGroup.getCheckedRadioButtonId();

        radioButton = findViewById(radioId);

        Toast.makeText(this, "You've selected: " + radioButton.getText(), Toast.LENGTH_SHORT).show();
    }
}

и вот мой xml:

<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity">

    <TextView
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_alignParentTop = "true"
        android:layout_centerHorizontal = "true"
        android:text = "Pick an Arithmetic Operation"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintLeft_toLeftOf = "parent"
        app:layout_constraintRight_toRightOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />

    <RadioGroup
        android:id = "@+id/radioGroup"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:layout_alignParentTop = "true"
        android:layout_marginTop = "49dp"
        android:orientation = "horizontal"
        android:layout_centerHorizontal = "true">

        <RadioButton
            android:id = "@+id/add"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:text = "+"
            android:layout_weight = "1"
            android:textAlignment = "center"/>

        <RadioButton
            android:id = "@+id/sub"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:layout_weight = "1"
            android:text = "-"
            android:textAlignment = "center"/>

        <RadioButton
            android:id = "@+id/prod"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:layout_weight = "1"
            android:text = "x"
            android:textAlignment = "center"/>

        <RadioButton
            android:id = "@+id/div"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:layout_weight = "1"
            android:text = "/"
            android:textAlignment = "center"/>
    </RadioGroup>

    <TextView
        android:id = "@+id/selection"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_above = "@+id/button_problem"
        android:layout_centerHorizontal = "true"
        android:layout_marginBottom = "-123dp"
        android:text = "You've selected: "
        android:textSize = "25sp"
        android:visibility = "invisible" />

    <Button
        android:id = "@+id/button_problem"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:layout_alignParentStart = "true"
        android:layout_alignParentTop = "true"
        android:layout_marginTop = "123dp"
        android:text = "GIVE ME A PROBLEM"
        tools:layout_editor_absoluteX = "135dp"
        tools:layout_editor_absoluteY = "32dp" />

    <TextView
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_centerInParent = "true"
        android:text = "Type your answer below"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintLeft_toLeftOf = "parent"
        app:layout_constraintRight_toRightOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />

    <Button
        android:id = "@+id/button_check"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:layout_alignParentBottom = "true"
        android:layout_centerHorizontal = "true"
        android:layout_marginBottom = "142dp"
        android:text = "CHECK MY ANSWER"
        tools:layout_editor_absoluteX = "202dp"
        tools:layout_editor_absoluteY = "37dp" />

    <EditText
        android:id = "@+id/solution"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_alignParentBottom = "true"
        android:layout_centerHorizontal = "true"
        android:layout_marginBottom = "217dp"
        android:ems = "10"
        android:inputType = "textPersonName" />

    <TextView
        android:id = "@+id/equation"
        android:layout_width = "170dp"
        android:layout_height = "52dp"
        android:layout_alignParentTop = "true"
        android:layout_centerHorizontal = "true"
        android:layout_marginTop = "193dp"
        android:text = "TextView"
        android:visibility = "invisible" />

    <TextView
        android:id = "@+id/answer_check"
        android:layout_width = "200dp"
        android:layout_height = "65dp"
        android:layout_alignParentBottom = "true"
        android:layout_centerHorizontal = "true"
        android:layout_marginBottom = "28dp"
        android:text = "TextView"
        android:visibility = "invisible" />

    <TextView
        android:id = "@+id/encouragement"
        android:layout_width = "156dp"
        android:layout_height = "wrap_content"
        android:layout_alignParentBottom = "true"
        android:layout_centerHorizontal = "true"
        android:layout_marginBottom = "108dp"
        android:text = "TextView"
        android:visibility = "invisible" />
</RelativeLayout>

Вы получаете сообщение об ошибке или трассировку стека во время сбоя приложения? Не могли бы вы рассказать нам об этом?

triplem 25.09.2018 06:55

Когда я нажимаю кнопку «Задай мне проблему», все приложение просто закрывается.

Chris Rushing 25.09.2018 22:17
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
1
2
40
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

При обработке события onClick "buttonChecked" приведение вашего типа недопустимо.

if (user_answer == (TextView) correct_answer){ //your code has EditText 
  support.setText("Keep up the good work!");
  buttonChecked.setEnabled(false);
}

объект "правильный_ответ" получается как

correct_answer = findViewById(R.id.answer_check);

который объявлен как «TextView».

<TextView
        android:id = "@+id/answer_check"
        android:layout_width = "200dp"
        android:layout_height = "65dp"
        android:layout_alignParentBottom = "true"
        android:layout_centerHorizontal = "true"
        android:layout_marginBottom = "28dp"
        android:text = "TextView"
        android:visibility = "invisible" />

Другие вопросы по теме