Исключение нулевого указателя в методе onCreate: попытка вызвать виртуальный метод для нулевого объекта - PullRequest
0 голосов
/ 08 апреля 2020

Я что-то упустил или сделал что-то не так в моем коде? Это показывает это, когда я запускаю:

Причина: java .lang.NullPointerException: Попытка вызвать виртуальный метод 'void android .widget.TextView.setText (java .lang. CharSequence) 'для ссылки на пустой объект com.haarismemon.forensiclab.test2.onCreate (test2. java: 47)

activity_test2. xml

<androidx.constraintlayout.widget.ConstraintLayout
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=".test2">


    <ProgressBar
        android:id="@+id/prog_timer"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:max="30"
        android:progress="45"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_timer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="TextView"
        android:textSize="24sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/prog_timer" />

    <TextView
        android:id="@+id/tv_score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/prog_timer" />

    <TextView
        android:id="@+id/question"
        android:layout_width="415dp"
        android:layout_height="150dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="30dp"
        android:text="TextView"
        android:textSize="24sp"
        android:gravity="center"
        app:layout_constraintEnd_toEndOf="@id/tv_timer"
        app:layout_constraintStart_toStartOf="@id/tv_score"
        app:layout_constraintTop_toBottomOf="@id/prog_timer" />

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/question">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:id="@+id/btn_answer0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:height="200dp"
                android:background="#FFC300 "
                android:text="Button" />

            <Button
                android:id="@+id/btn_answer1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:height="200dp"
                android:background="#FFFC33"
                android:text="Button" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:id="@+id/btn_answer2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:height="200dp"
                android:background="#FF5733 "
                android:text="Button" />

            <Button
                android:id="@+id/btn_answer3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:height="200dp"
                android:background="#C70039"
                android:text="Button" />
        </TableRow>
    </TableLayout>

    <TextView
        android:id="@+id/tv_bottommessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginBottom="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:text="TextView"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

test2. java


import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Random;

public class test2 extends AppCompatActivity {
    Button  btn_answer0, btn_answer1, btn_answer2, btn_answer3;
    TextView question,  tv_timer, tv_bottommessage, tv_score;
    ProgressBar prog_timer;

    private Question2 mQuestion = new Question2 ();
    private String mAnswer;
    private int mScore = 0;
    private int mQuestionLength = mQuestion.myQuestion.length;


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

        final Random r = new Random();


        btn_answer0 = findViewById(R.id.btn_answer0);
        btn_answer1 = findViewById(R.id.btn_answer1);
        btn_answer2 = findViewById(R.id.btn_answer2);
        btn_answer3 = findViewById(R.id.btn_answer3);
        tv_score = findViewById(R.id.tv_score);
        question = findViewById(R.id.question);
        tv_bottommessage = findViewById(R.id.tv_bottommessage);
        tv_timer = findViewById(R.id.tv_timer);
        prog_timer = findViewById(R.id.prog_timer);

        tv_score.setText("Score: "+ mScore);

        updatedCurrentQuestion(r.nextInt(mQuestionLength));

        btn_answer0.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if (btn_answer0.getText()==mAnswer) {
                    mScore++;
                    tv_score.setText("Score: " + mScore);
                    updatedCurrentQuestion(r.nextInt(mQuestionLength));
                }else{
                    gameisover();
                }
            }
        });

        btn_answer1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if (btn_answer1.getText()==mAnswer) {
                    mScore++;
                    tv_score.setText("Score: " + mScore);
                    updatedCurrentQuestion(r.nextInt(mQuestionLength));
                }else{
                    gameisover();
                }
            }
        });

        btn_answer2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if (btn_answer2.getText()==mAnswer) {
                    mScore++;
                    tv_score.setText("Score: " + mScore);
                    updatedCurrentQuestion(r.nextInt(mQuestionLength));
                }else{
                    gameisover();
                }
            }
        });

        btn_answer3.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if (btn_answer3.getText()==mAnswer) {
                    mScore++;
                    tv_score.setText("Score: " + mScore);
                    updatedCurrentQuestion(r.nextInt(mQuestionLength));
                }else{
                    gameisover();
                }
            }
        });
    }

    private void gameisover(){
        AlertDialog.Builder alertDialogbuilder = new AlertDialog.Builder(test2.this);
        alertDialogbuilder
                .setMessage("YOUR GAME IS OVER!"+ mScore)
                .setCancelable(false)
                .setPositiveButton("Start New Game.", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        startActivity(new Intent(getApplicationContext(), test2.class));
                        finish();
                    }
                })
                .setNegativeButton("Exit.", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
        AlertDialog alertDialog = alertDialogbuilder.create();
        alertDialog.show();
    }

    private void updatedCurrentQuestion(int i){
        question.setText(mQuestion.getQuestion(i));
        btn_answer0.setText(mQuestion.getChoices0(i));
        btn_answer1.setText(mQuestion.getChoices1(i));
        btn_answer2.setText(mQuestion.getChoices2(i));
        btn_answer3.setText(mQuestion.getChoices3(i));
        mAnswer = mQuestion.getCorrectAnswer(i);

    }
}

Ответы [ 2 ]

0 голосов
/ 09 апреля 2020

Теперь я знаю, в чем проблема .. Проблема в

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mobile_forensic);

Это должно быть

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test2);

Извините за мой плохой Энгли sh ..

0 голосов
/ 08 апреля 2020

Эта ошибка обычно возникает, когда идентификатор виджета ошибочно сопоставляется методом findViewById. Попробуйте изменить свой код с этого:

tv_score = (TextView)findViewById(R.id.tv_score);

на это:

tv_score = findViewById(R.id.tv_score);

Кроме того, перепроверьте идентификатор, используемый из findViewById способ.

...