【问题标题】:NullPointerException when trying to print random values in android studio [duplicate]尝试在android studio中打印随机值时出现NullPointerException [重复]
【发布时间】:2015-07-29 21:44:49
【问题描述】:

我在第 99 行和第 77 行不断收到空指针异常,这是我尝试打印由随机类创建的随机值(第 99 行)的地方,也是我调用 setQuestion 方法的地方(第 77 行。randomNum 到layout_game xml 文件。我不知道为什么我得到一个空值,因为当我将值记录到控制台时,它说正在生成值。

package com.grantsolutions.mathgamechapter1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;


public class GameActivity extends Activity implements OnClickListener {
int correctAnswer;
Button buttonObjectChoice1;
Button buttonObjectChoice2;
Button buttonObjectChoice3;
TextView textObjectPartA //it says that textObjectPartA and B are never used;
TextView textObjectPartB;
TextView textObjectScore;
TextView textObjectLevel;
int currentScore;
int currentLevel = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_game);






    //declaring variables for game

    //no longer being declared

    /*int partA = 2;
    int partB = 2;
    correctAnswer = partA * partB;
    int wrongAnswer1 = correctAnswer - 1;
    int wrongAnswer2 = correctAnswer + 1;
    /*this is where we link the variables
    from  the java code to the button UI in
     activity_game xml itself
     */
    TextView textObjectPartA = (TextView) findViewById(R.id.holdTextA);

    TextView textObjectPartB = (TextView) findViewById(R.id.holdTextB);
    textObjectScore = (TextView) findViewById(R.id.textLevel);
    textObjectLevel = (TextView) findViewById(R.id.textScore);

    buttonObjectChoice1 =
            (Button) findViewById(R.id.choice1);

    buttonObjectChoice2 =
            (Button) findViewById(R.id.choice2);

    buttonObjectChoice3 =
            (Button) findViewById(R.id.choice3);
    /*Use the setText method of the class on our objects
    to show our variable values on the UI elements.
    Similar to outputting to the console in the exercise,
    only using the setText method*/


    //telling the console to listen for button clicks from the user
    buttonObjectChoice1.setOnClickListener(this);
    buttonObjectChoice2.setOnClickListener(this);
    buttonObjectChoice3.setOnClickListener(this);
    setQuestion();



}


void setQuestion() {
    Random randomNum;
    randomNum = new Random();

    int partA = 0;
    int numberRange = currentLevel * 3;
    partA = randomNum.nextInt(numberRange) + 1;
     //removes possibility of a zero value
    int partB = randomNum.nextInt(numberRange) + 1;

    correctAnswer = partA * partB;
    Log.i("info", ""+partA);
    Log.i("info", ""+partB);
    Log.d("info", ""+partA);
    int wrongAnswer1 = correctAnswer - 2;
    int wrongAnswer2 = correctAnswer + 2;
    Log.i("info", ""+partA);
    Log.i("info", ""+partB);
    textObjectPartA.setText(""+partA); //error here
    textObjectPartB.setText(""+partB);
    //case for setting multiple choice buttons
    int buttonLayout = randomNum.nextInt(3);
    switch (buttonLayout) {
        case 0:
            buttonObjectChoice1.setText("" + correctAnswer);
            buttonObjectChoice2.setText("" + wrongAnswer1);
            buttonObjectChoice3.setText("" + wrongAnswer2);
            break;
        case 1:
            buttonObjectChoice2.setText("" + correctAnswer);
            buttonObjectChoice1.setText("" + wrongAnswer1);
            buttonObjectChoice3.setText("" + wrongAnswer2);
            break;
        case 2:
            buttonObjectChoice3.setText("" + correctAnswer);
            buttonObjectChoice1.setText("" + wrongAnswer1);
            buttonObjectChoice2.setText("" + wrongAnswer2);
            break;
    }


}

void updateScoreAndLevel(int answerGiven) {
    if (isCorrect(answerGiven)) {
        for (int i = 1; i <= currentLevel; i++) {
            currentScore = currentScore + i;

        }
    } else {
        currentLevel = 1;
        currentScore = 0;

    }

    currentLevel++;

}


boolean isCorrect(int answerGiven) {
    boolean correctTrueOrFalse = true;
    if (answerGiven == correctAnswer) {//YAY!
        Toast.makeText(getApplicationContext(), "Well Done", Toast.LENGTH_LONG).show();

    }
    else {//If wrong print this instead
        Toast.makeText(getApplicationContext(), "You're wrong", Toast.LENGTH_SHORT).show();
    }  //case for each button being made
    correctTrueOrFalse = false;

    return correctTrueOrFalse;
}


    @Override
    public void onClick (View view){
        //declaring a new int to use in all cases
        int answerGiven;

        switch (view.getId()) {
            //case for each button being made

            case R.id.choice1:
                //button1 information goes here
                //initialize a new integer with the value
                //contained in buttonObjectChoice1
                answerGiven = Integer.parseInt("" +       buttonObjectChoice1.getText());
                //check if the right answer

                break;

            case R.id.choice2:
                //button2 information goes here
                answerGiven = Integer.parseInt("" + buttonObjectChoice2.getText());


                break;

            case R.id.choice3:
                //button 3 information goes here
                answerGiven = Integer.parseInt("" + buttonObjectChoice3.getText());
                break;


        }

    }


}

此处为第 99 行和第 77 行的代码 sn-p

第 77 行

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







    TextView textObjectPartA = (TextView) findViewById(R.id.holdTextA);

    TextView textObjectPartB = (TextView) findViewById(R.id.holdTextB);
    textObjectScore = (TextView) findViewById(R.id.textLevel);
    textObjectLevel = (TextView) findViewById(R.id.textScore);

    buttonObjectChoice1 =
            (Button) findViewById(R.id.choice1);

    buttonObjectChoice2 =
            (Button) findViewById(R.id.choice2);

    buttonObjectChoice3 =
            (Button) findViewById(R.id.choice3);
    /*Use the setText method of the class on our objects
    to show our variable values on the UI elements.
    Similar to outputting to the console in the exercise,
    only using the setText method*/


    //telling the console to listen for button clicks from the user
    buttonObjectChoice1.setOnClickListener(this);
    buttonObjectChoice2.setOnClickListener(this);
    buttonObjectChoice3.setOnClickListener(this);
    setQuestion(); //code error shown in this line



}

第 99 行

   Log.i("info", ""+partA);
    Log.i("info", ""+partB); 
    textObjectPartA.setText(""+partA); //error here
    textObjectPartB.setText(""+partB);

layout_game 文件

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="2"
    android:id="@+id/holdTextA"
    android:layout_marginTop="44dp"
    android:textSize="50sp"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginLeft="44dp"
    android:layout_marginStart="44dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="X"
    android:id="@+id/textView4"
    android:layout_alignTop="@+id/holdTextA"
    android:layout_centerHorizontal="true"
    android:textSize="50sp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="4"
    android:id="@+id/holdTextB"
    android:textSize="50sp"
    android:layout_above="@+id/textView6"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginRight="53dp"
    android:layout_marginEnd="53dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="="
    android:id="@+id/textView6"
    android:layout_marginTop="118dp"
    android:layout_below="@+id/textView4"
    android:layout_alignLeft="@+id/textView4"
    android:layout_alignStart="@+id/textView4"
    android:textSize="60sp" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/choice1"
    android:text="2"
    android:textSize="40sp"
    android:layout_alignParentBottom="true"
    android:layout_alignRight="@+id/holdTextA"
    android:layout_alignEnd="@+id/holdTextA"
    android:layout_marginBottom="37dp" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="4"
    android:id="@+id/choice2"
    android:layout_alignBottom="@+id/choice1"
    android:layout_alignLeft="@+id/holdTextB"
    android:layout_alignStart="@+id/holdTextB"
    android:textSize="40sp" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="3"
    android:id="@+id/choice3"
    android:layout_alignBottom="@+id/choice1"
    android:layout_centerHorizontal="true"
    android:layout_alignTop="@+id/choice1"
    android:textSize="40sp" />

【问题讨论】:

  • 我想作为常见问题的副本关闭(你们都知道它是什么)由于代码太多而偏离主题。唉,我必须选择一个...... :(
  • 你也可以粘贴异常吗?

标签: java android random nullpointerexception settext


【解决方案1】:

在你的

onCreateView()

你已经声明了

TextView textObjectPartA = (TextView) findViewById(R.id.holdTextA);

这样你的全局变量 textObjectPartA 没有被设置,因此空点异常。

【讨论】:

  • 我应该把它放在哪里,在 oncreate 部分之外?
  • 它应该只是 'textObjectPartA = (TextView) findViewById(R.id.holdTextA);'这样,您的全局变量 textObjectPartA 将具有一个不为空的值。这就是为什么它说从未使用过 textObjectPartA 的原因(在此处阅读您的评论)
  • 'TextView textObjectPartA = (TextView) findViewById(R.id.holdTextA);'正在为 onCreate 方法创建一个本地变量..
  • 非常感谢,我什至没有看到这个问题。 #noobmistakes
  • 发生在每个人身上
猜你喜欢
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 2015-09-01
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
相关资源
最近更新 更多