简体   繁体   中英

Getting Java Lang Null pointer exception in Android

I've been coding an android app and i've suddenly started getting an error, the error log says there is Java.Lang.Null.pointer.exception on line 23 of my Game.java yet none of the code concerning that has been changed. Here is the code: Any ideas?

Main class

public void onClick(View v) {
    switch (v.getId()) {        
    case R.id.about_button:
        Intent i = new Intent(this, About.class);
        startActivity(i);
        break;
    case R.id.ext_button:
        finish();
        break;

    case R.id.new_button:

        openNewGameDialog();
        break;
    }
}

private void openNewGameDialog() {

    new AlertDialog.Builder(this)

    .setTitle(R.string.diff_head)

    .setItems(R.array.difficulty,

     new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialoginterface, 
                int i) {

            startGame(i);

        }
    })

    .show();
}


private void startGame(int i) {

    Intent intent = new Intent(this, Game.class);

    intent.putExtra(Game.KEY_DIFFICULTY, i);

    startActivity(intent); 
}

Game.java

public class Game extends Activity {

public static final String KEY_DIFFICULTY = "w1279057.CW1.difficulty";
public static final int DIFFICULTY_NOVICE = 0;
public static final int DIFFICULTY_EASY = 1;
public static final int DIFFICULTY_MEDIUM = 2;
public static final int DIFFICULTY_GURU = 3;




            Random rand = new Random();


line 23 >>  int diff = getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_NOVICE);

@Override   
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

If that's the line where it's happening, then that means that the value being returned from getIntent() is null. This is why you should always avoid calling methods on the return results of method calls (see Law of Demeter ).

You should double check and see how this activity is getting started. Chances are the troubles are there.

You didn't upload enough code to make it clear.. But if I had to guess.. getIntent() will only return a non-null value if its being called from the startGame() method. You will get a nullpointer if youre activity restarts (ie orientation change). try something like this.

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState
    int diff;
    if(savedInstanceState == null)
         diff = getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_NOVICE);
}

and then if you want to save the state look at the method onRestoreInstanceState(Bundle outstate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM