dimanche 9 octobre 2016

Attempt to invoke virtual method 'int java.util.Random.nextInt(int)' on a null object reference

I've got the exact problem as the question: Attempt to invoke virtual method 'int java.util.Random.nextInt(int)' on a null object reference [Android] . But I've already instanceiated the Random variable with Random but it still doesn't work. Anyone knows why?

.
.
.
import java.util.Random;

public class game_page extends AppCompatActivity {

    private TextView gameProblem;
    private int leftNumber;
    private int rightNumber;
    private EditText solution;
    private String operator;
    private int sum;

    private Random r = new Random();

    private int difficulty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_page);
        gameProblem = (TextView)findViewById(R.id.game_problem);
        solution = (EditText)findViewById(R.id.solution);

        setDifficulty();
        newProblem();
    }

    //1 = easy
    private void setDifficulty() {
        this.difficulty = 1;
    }

    private void newProblem() {
        if(difficulty == 1){
            leftNumber = r.nextInt(0) + 10;
            rightNumber = r.nextInt(0) + 10;
            operator = "+";
            sum = Integer.parseInt(leftNumber + operator + rightNumber);
            gameProblem.setText(leftNumber + operator + rightNumber + "=");
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire