Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException from getExtras()

I'm creating an intent to transfer data from one activity to another like this :

Intent intent = new Intent(this, ActivityHighScore.class);
    intent.putExtra("USERNAME", username);
    intent.putExtra("PLAYERMOVES", playerMoves);

    this.startActivity(intent);

Then i want to check if all of this data exists as the activity starts, as it can be started from other sources without this data being set. Im using this statement:

        Bundle bundle = getIntent().getExtras();

    if (!bundle.getString("USERNAME").equals(null) && bundle.getInt("PLAYERMOVES") != 0){
        String username = bundle.getString("USERNAME");
        int playerMoves = bundle.getInt("PLAYERMOVES");
        addHighScore(username, playerMoves);

    }   

But this causes a null pointerexception and I'm entirely sure how. I thought I was getting to grips with Strings and .equals(), but I think its that... Any help would be greatly appreciated. Thanks.

like image 920
Benny292 Avatar asked May 20 '12 14:05

Benny292


2 Answers

Replace

Bundle bundle = getIntent().getExtras();

    if (!bundle.getString("USERNAME").equals(null) && bundle.getInt("PLAYERMOVES") != 0){
        String username = bundle.getString("USERNAME");
        int playerMoves = bundle.getInt("PLAYERMOVES");
        addHighScore(username, playerMoves);

    } 

with

 if (getIntent().getStringExtra("USERNAME") != null && (getIntent().getIntExtra("PLAYERMOVES", 0) != 0){
        String username = bundle.getString("USERNAME");
        int playerMoves = bundle.getInt("PLAYERMOVES");
        addHighScore(username, playerMoves);

  } 
like image 146
Jeshurun Avatar answered Nov 06 '22 15:11

Jeshurun


Well, I had a similar problem. In my case the NullPointerException happened when I checked if my bundle.getString() was equal to null.

Here is how I solved it, in my case:

Intent intent = getIntent();        
if(intent.hasExtra("nomeUsuario")){
    bd = getIntent().getExtras();
    if(!bd.getString("nomeUsuario").equals(null)){
        nomeUsuario = bd.getString("nomeUsuario");
    }
}
like image 35
JúlioCézar Avatar answered Nov 06 '22 15:11

JúlioCézar