-1

I'm making an Android app, it should ask for arithmetic equations and check the answer. There should be different difficulty levels as well. My app crashes when choosing the difficulty level from AlertDialog. I have no errors in Android Studio.

Here is the code for choosing level:

public void onClick(View view) {
    if(view.getId()==R.id.play_btn){
        //play button
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose a level")
                .setSingleChoiceItems(levelNames, 0, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //start gameplay
                        startPlay(which);
                    }
                });
        AlertDialog ad = builder.create();
        ad.show();
    }

private void startPlay(int chosenLevel){
    //start gameplay
    Intent playIntent = new Intent(this, PlayGame.class);
    playIntent.putExtra("level", chosenLevel);
    this.startActivity(playIntent);
}

Can someone help me understand why my app crashes?

Here is the log:

9758-9758/org.example.braintraining E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: org.example.braintraining, PID: 9758
                                                                     java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.braintraining/org.example.braintraining.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
                                                                         at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:145)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5942)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at java.lang.reflect.Method.invoke(Method.java:372)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
                                                                      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
                                                                         at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
                                                                         at android.app.Activity.performCreate(Activity.java:6289)
                                                                         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758) 
                                                                         at android.app.ActivityThread.access$900(ActivityThread.java:177) 
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448) 
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                         at android.os.Looper.loop(Looper.java:145) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5942) 
                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                         at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388) 
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) 

Here is the code for onCreate method of PlayGame class:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_playgame);
    gamePrefs = getSharedPreferences(GAME_PREFS, 0);

    //text and image views
    question = (TextView)findViewById(R.id.question);
    answerTxt = (TextView)findViewById(R.id.answer);
    response = (ImageView)findViewById(R.id.response);
    scoreTxt = (TextView)findViewById(R.id.score);

    //hide tick cross initially
    response.setVisibility(View.INVISIBLE);

    //number, enter and clear buttons
    btn1 = (Button)findViewById(R.id.btn1);
    btn2 = (Button)findViewById(R.id.btn2);
    btn3 = (Button)findViewById(R.id.btn3);
    btn4 = (Button)findViewById(R.id.btn4);
    btn5 = (Button)findViewById(R.id.btn5);
    btn6 = (Button)findViewById(R.id.btn6);
    btn7 = (Button)findViewById(R.id.btn7);
    btn8 = (Button)findViewById(R.id.btn8);
    btn9 = (Button)findViewById(R.id.btn9);
    btn0 = (Button)findViewById(R.id.btn0);
    enterBtn = (Button)findViewById(R.id.enter);
    clearBtn = (Button)findViewById(R.id.clear);

    //listen for clicks
    btn1.setOnClickListener(this);
    btn2.setOnClickListener(this);
    btn3.setOnClickListener(this);
    btn4.setOnClickListener(this);
    btn5.setOnClickListener(this);
    btn6.setOnClickListener(this);
    btn7.setOnClickListener(this);
    btn8.setOnClickListener(this);
    btn9.setOnClickListener(this);
    btn0.setOnClickListener(this);
    enterBtn.setOnClickListener(this);
    clearBtn.setOnClickListener(this);

    //get passed level number
    if(savedInstanceState!=null){
        //restore state
    }
    else{
        Bundle extras = getIntent().getExtras();
        if(extras !=null)
        {
            int passedLevel = extras.getInt("level", -1);
            if(passedLevel>=0) level = passedLevel;
            level=savedInstanceState.getInt("level");
            int exScore = savedInstanceState.getInt("score");
            scoreTxt.setText("Score: "+exScore);
        }
    }

    //initialize random
    random = new Random();
    //play
    chooseQuestion();
}
Vahagn
  • 11
  • 5

1 Answers1

0

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference at org.example.braintraining.PlayGame.onCreate(PlayGame.java:10‌​4)

Either the code might be failing in two scenarios:

  1. You are starting new activity by passing the playIntent. Please check the code in PlayGame.java, in onCreate() you should be getting the string value (level) from Intent rather than from Bundle, something like
 String chosenLevel;
 Intent i = this.getIntent();
 if(i != null){
  chosenLevel = i.getStringExtra("level");
 }

2.if you are rotating the screen, once you are in the play game activity where you are not saving the required value before the activity is destroyed and trying to retrieve it back once the activity is recreated .

Solution would be to use the put methods to store values in onSaveInstanceState():

protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putString("value", chosenLevel);
} 

And restore the value from Bundle in onCreate() or you can use onRestoreInstanceState(), which is called after onStart(), whereas onCreate() is called before onStart().:

public void onCreate(Bundle bundle) {
if (bundle!= null){
chosenValue = bundle.getString("value");
 } 
} 
Koushik
  • 26
  • 2