Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to use the rng from java when I click a button but each time I click it the program crashes and gives me the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.Random.nextInt(int)' on a null object reference
at me.test.first.MainActivity.onGenPress(MainActivity.java:25)

Button Press Method

public void onGenPress(View v){
        TextView tv = (TextView) findViewById(R.string.copper);
        int number = 1 + dice.nextInt(rollProgressMA);
        co.copper += number;
        tv.setText("Copper: " + co.copper + " + " + number);
}

Objects involved in class

CoinTracker co = new CoinTracker();
RollProgress rpo = new RollProgress();
private Random dice;
private int rollProgressMA = rpo.rollProgress;

Int value from RollProgress class

public int rollProgress = 1;

Thanks in advance for any attempts at solving/solutions.

like image 749
Juan Avatar asked Mar 04 '26 06:03

Juan


1 Answers

private Random dice;

I don't see any code that initializes the dice variable before you use it in dice.nextInt(rollProgressMA);.

Just change the declaration to :

private Random dice = new Random();

like image 90
Eran Avatar answered Mar 05 '26 21:03

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!