У меня нет ошибок, но мое приложение закрывается - PullRequest
0 голосов
/ 08 марта 2020

У меня нет проблем на основе кодов, но почему мое приложение продолжает закрываться, когда я запускаю его, я новичок в java Я делаю приложение для викторины для моей диссертации PS Я только копирую коды в YouTube и редактирую Пожалуйста, помогите мне открыть мое приложение

MainActivity. java

LtoQuiz. java

package com.example.ltoexam;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class LtoQuiz extends AppCompatActivity {

    private com.example.ltoexam.QuestionLibrary nQuestionLibrary = new com.example.ltoexam.QuestionLibrary();

    private TextView nScoreView;
    private TextView nQuestionView;
    private Button nButtonChoice1;
    private Button nButtonChoice2;
    private Button nButtonChoice3;

    private String nAnswer;
    private int nScore = 0;
    private int nQuestionNumber = 0;




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

        nScoreView = (TextView) findViewById(R.id.score);
        nQuestionView = (TextView) findViewById(R.id.question);
        nButtonChoice1 = (Button) findViewById(R.id.choice1);
        nButtonChoice2 = (Button) findViewById(R.id.choice2);
        nButtonChoice3 = (Button) findViewById(R.id.choice3);

        updateQuestion();

        //Start of Button Listener for Button1
        nButtonChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here
                if (nButtonChoice1.getText() == nAnswer){
                    nScore =nScore + 1;
                    updateScore(nScore);
                    updateQuestion();
                    //This line of code is optional
                    Toast.makeText(LtoQuiz.this, "correct", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(LtoQuiz.this, "wrong", Toast.LENGTH_SHORT).show();
                    updateQuestion();
                }
            }
        });

        //End of Button Listener for Button2


        //Start of Button Listener for Button2
        nButtonChoice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here
                if (nButtonChoice2.getText() == nAnswer){
                    nScore =nScore + 1;
                    updateScore(nScore);
                    updateQuestion();
                    //This line of code is optional
                    Toast.makeText(LtoQuiz.this, "correct", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(LtoQuiz.this, "wrong", Toast.LENGTH_SHORT).show();
                    updateQuestion();
                }
            }
        });

        //End of Button Listener for Button2


        //Start of Button Listener for Button3
        nButtonChoice3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here
                if (nButtonChoice3.getText() == nAnswer){
                    nScore =nScore + 1;
                    updateScore(nScore);
                    updateQuestion();
                    //This line of code is optional
                    Toast.makeText(LtoQuiz.this, "correct", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(LtoQuiz.this, "wrong", Toast.LENGTH_SHORT).show();
                    updateQuestion();
                }
            }
        });

        //End of Button Listener for Button2




    }
    private void updateQuestion(){
        nQuestionView.setText(nQuestionLibrary.getQuestion(nQuestionNumber));
        nButtonChoice1.setText(nQuestionLibrary.getChoice1(nQuestionNumber));
        nButtonChoice2.setText(nQuestionLibrary.getChoice2(nQuestionNumber));
        nButtonChoice3.setText(nQuestionLibrary.getChoice3(nQuestionNumber));

        nAnswer = nQuestionLibrary.getCorrectAnswer(nQuestionNumber);
        nQuestionNumber++;
    }


    private void updateScore(int point){
        nScoreView.setText("" + nScore);

    }

}

QuestionLibrary. java

package com.example.ltoexam;

public class QuestionLibrary {

    private String nQuestions [] = {
            "1.The three colors of the traffic lights are:",
            "2.Yellow triangular signs provide what kind of information",
            "3.Which of the following traffic signs are blue?",
            "4.Steady green light means",
            "5.A flashing yellow light at a road crossing signifies",
            "6.A solid white line on the right edge of the highway slopes in towards your left. This shows that",
            "7.You are in a No-Passing zone when the center of the road is marked by"

    };

    private String nChoices [] [] = {
            {"red, green and yellow", "red, green and blue", "yellow, green and blue"},
            {"warning", "hospital across", "speed limit"},
            {"regulatory signs", "information signs", "danger warning signs"},
            {"you must yield to all pedestrians and other motorists using the intersection", "go, it is safe to do so", "proceed cautiously through the intersection before the light changes to red."},
            {"Caution - slow down and proceed with caution", "Stop and stay until light stops flashing", "Wait for the green light"},
            {"there is an intersection joint ahead", "the road will get narrower", "you are approaching a construction area"},
            {"a broken yellow line","a broken white line","two solid yellow lines"}




    };

    private String nCorrectAnsers[] = {"red, green and yellow", "warning", "information signs", "go, it is safe to do so", "Caution - slow down and proceed with caution", "the road will get narrower", "two solid yellow lines"};

    public String getQuestion(int a) {
        String question = nQuestions[a];
        return question;
    }

    public String getChoice1(int a) {
        String choice0 = nChoices[a] [0];
        return choice0;
    }

    public String getChoice2(int a) {
        String choice1 = nChoices[a] [1];
        return choice1;
    }

    public String getChoice3(int a) {
        String choice2 = nChoices[a] [2];
        return choice2;
    }

    public String getCorrectAnswer(int a) {
        String answer = nCorrectAnsers[a];
        return answer;
    }


}

activity_main. xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="16dp"
    android:paddingTop="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="16dp"
    tools:context=".LtoQuiz">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:layout_marginBottom="40dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Score"
            android:textSize="20sp"
            android:layout_alignParentLeft="true"
            android:id="@+id/score_text"/>


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:layout_alignParentRight="true"
            android:text="0"
            android:id="@+id/score"/>




    </RelativeLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:text="Which thing is alive?"
        android:textSize="20sp"
        android:padding="8dp"
        android:layout_marginBottom="40dp"
        android:id="@+id/question"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="bird"
        android:background="#0091EA"
        android:textColor="#fff"
        android:padding="8dp"
        android:layout_marginBottom="24dp"
        android:id="@+id/choice1"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="door"
        android:background="#0091EA"
        android:textColor="#fff"
        android:padding="8dp"
        android:layout_marginBottom="24dp"
        android:id="@+id/choice2"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="rock "
        android:background="#0091EA"
        android:textColor="#fff"
        android:padding="8dp"
        android:layout_marginBottom="24dp"
        android:id="@+id/choice3"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Quit"
        android:background="#871C1C"
        android:textColor="#fff"
        android:padding="8dp"
        android:layout_marginBottom="24dp"
        android:id="@+id/quit"/>



</LinearLayout>

Myerror

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ltoexam, PID: 4530
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.ltoexam/com.example.ltoexam.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.ltoexam.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.ltoexam-M42DBs42t6LEwfwChdwEyw==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.ltoexam-M42DBs42t6LEwfwChdwEyw==/lib/arm64, /system/lib64, /vendor/lib64]]
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2793)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2979)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6754)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.ltoexam.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.ltoexam-M42DBs42t6LEwfwChdwEyw==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.ltoexam-M42DBs42t6LEwfwChdwEyw==/lib/arm64, /system/lib64, /vendor/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1180)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2979) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:192) 
        at android.app.ActivityThread.main(ActivityThread.java:6754) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828) 
I/Process: Sending signal. PID: 4530 SIG: 9
Disconnected from the target VM, address: 'localhost:8614', transport: 'socket'

logcat не завершен

08 18: 54: 20.316 595-595 /? V / LocSvc_HIDL_IzatSubscription: [wifiSupplicantStatusUpdate] [682] [HS] <<<< = [HC] 2020-03-08 18: 54: 20.316 1537-1911 /? D / ConnectivityService: игнорирование неизменного состояния сети без изменений 2020-03-08 18: 54: 20.331 1537-1911 /? D / ConnectivityService: обновление свойств LinkProperties для NetworkInfo [WIFI () - 151]; создано = ложь; everConnected = false 2020-03-08 18: 54: 20.338 595-595 /? V / LocSvc_HIDL_IzatSubscription: [wifiSupplicantStatusUpdate] [682] [HS] <<<< = [HC] 2020-03-08 18: 54: 20.376 1537-3091 /? I / chatty: uid = 1000 (system) DhcpClient истекает 54 строки 2020-03-08 18: 54: 20.377 1537-3093 /? I / chatty: uid = 1000 (system) Поток 279 истекает 3 строки 2020-03-08 18: 54: 20.444 1537-2219 /? D / DisplayPowerController: mSettingBrightness = -1 как запрос 233 2020-03-08 18: 54: 21.273 2895-2895 /? I / Process: отправка сигнала. PID: 2895 SIG: 9 2020-03-08 18: 54: 21,306 1537-3661 /? I / ActivityManager: процесс com.bbk.theme.networkChange (pid 2895) умер: cch + 2CEM 2020-03-08 18: 54: 21.309 3437-3473 /? E / VivoPu sh .AbeProcessObserver: (3437) удалить ошибку pid: pids is null 2020-03-08 18: 54: 21.309 1537-1972 /? D / ScreenBrightnessModeRestore: имя пакета com.bbk.themewith: 10051 2020-03-08 18: 54: 21,309 1537-1972 /? D / ScreenBrightnessModeRestore: onProcessDiedInner, pid = 2895, mCurrent </p>

1 Ответ

1 голос
/ 08 марта 2020

Здравствуйте, если вы проверите эту часть сообщения об ошибке:

: java.lang.ClassNotFoundException: Didn't find class"com.example.ltoexam.MainActivity"

Вы видите, что android studio ищет этот класс MainActivity. И из быстрого просмотра информации, которую вы предоставляете, нет класса MainActivity. Этот класс сначала вызывается при запуске приложения и имеет макет этого Activity_main. (он должен называться MainActivity.class)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...