-1

I'm trying to retrieve a bundle from another activity but when I try this, the following error appears in my logs: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference

The part of the code where I try to retrieve and show the bundle is this:

Bundle bundlefrankrijk = getIntent().getExtras();
    int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk");

    TextView highscoreLabelfranrkijk = (TextView) findViewById(R.id.highscorefrankrijk);

    SharedPreferences settingsfrankrijk = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
    int highScorefrankrijk = settingsfrankrijk.getInt("HIGH_SCORE", 0);

    if (scorefrankrijk > highScorefrankrijk) {
        highscoreLabelfranrkijk.setText("High Score : " + scorefrankrijk);

        SharedPreferences.Editor editor = settingsfrankrijk.edit();
        editor.putInt("HIGH_SCORE", scorefrankrijk);
        editor.commit();
    } else {
        highscoreLabelfranrkijk.setText("High Score : " + highScorefrankrijk);
    }

This is how I'm sending the intent to the current activity:

Intent i = new Intent(QuizActivityFrankrijk.this, 
QuizResultaatFrankrijk.class);
            Bundle bundlefrankrijk = new Bundle(0);
            bundlefrankrijk.putInt("finalScoreFrankrijk", mScoreFrankrijk);
            i.putExtras(bundlefrankrijk);
            QuizActivityFrankrijk.this.finish();
            startActivity(i);

Thanks in advance!

JansenN
  • 33
  • 8

1 Answers1

0

Better if you could post the code to see how you are sending the intent with extras to current activity too, for what I´m seeing here, the error is in this line:

Bundle bundlefrankrijk = getIntent().getExtras(); // is returning null object

And when youre trying to:

int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk"); // NullPointerException throwed

Cause your bundle is null from beginning, you should check if you´re sending correctly the intent with extras, please use the method:

mIntent.putExtra("key", intValue)

and check that youre receiving it like this:

if (getIntent().getExtras() != null){    
     getIntent().getExtras().getInt("key");}

or just like this too:

if (getIntent().getExtras() != null){
     getIntent().getExtras().get("key");}

Remember, if the key is just different in some character, it will return NULL.

Please read this for more info: https://developer.android.com/reference/android/content/Intent.html

Crono
  • 2,024
  • 18
  • 16
  • I could add: use constants as keys as a typo is very easy to make. Plus it's easier to trace where the key is used. – Eselfar Oct 12 '17 at 22:30
  • I've added the code where you can see how I am sending the intent to the current activity, but I still don't know how to adapt your answer to my code – JansenN Oct 12 '17 at 23:57