0

Code on sender class:

public void sendQuestion(){
       Random randomNumber = new Random();
       final int rand = randomNumber.nextInt(19)+1;
       Intent numbers = new Intent(this, Questions.class);
       numbers.putExtra("randomNumber", rand);
       startActivity(numbers);

Code on receiver class:

public class Questions extends Activity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    question();
}

int questionNumber = getIntent().getExtras().getInt("randomNumber");
public void question() {
    String questionString = "Wrong";
    switch (questionNumber) {

Why am I getting this error?

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ryan
  • 65
  • 1
  • 5

2 Answers2

1

You seem to have called getIntent() as a field of the class, at which point the Intent has not been assigned.

You can declare that int as a field, but you should assign it from the intent within the onCreate, or other lifecycle method

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

You should move the int questionNumber = getIntent().getExtras().getInt("randomNumber"); so it will happen inside onCreate. Also, null checking couldn't hurt :P.

For example:

int questionNumber;

private void getIntentExtras()
{
    if(getIntent() != null && getIntent.getExtras() != null)
    {
        questionNumber = getIntent().getExtras().getInt("randomNumber");
    }
}
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Shahar.bm
  • 169
  • 8