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

十年热恋 提交于 2019-12-10 20:32:19

问题


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.


回答1:


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();



来源:https://stackoverflow.com/questions/26562162/attempt-to-invoke-virtual-method-int-java-util-random-nextintint-on-a-null-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!