Cheat activity stops working


#1

hi I’m at the end of chapter 5.
My app does not show the answer for the questions, the second avctivity gets initialized but it stops working as soon as a hit the button.

here is my code:

QuizActivity.java

[code]//this is our main control class
package com.example.geoquiz;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class QuizActivity extends Activity {
private static final String TAG = “QuizActivity”;
private static final String KEY_INDEX = “index”;

// we are encapsulating the code into a private method for updating the question
private void updateQuestion() {
	
    int question = mQuestionBank[mCurrentIndex].getQuestion();
    mQuestionTextView.setText(question);
}

// we are encapsulating the code into a private method for updating the answer
private void checkAnswer(boolean userPressedTrue) {

	//This method will accept a boolean variable that identifies whether the user pressed True or False.
	//Then, it will check the user’s answer against the answer in the current TrueFalse object.
	//Finally, after determining whether the user answered correctly, it will make a Toast that displays
	//the appropriate message to the user.  
	
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();

    int messageResId = 0;
    
    if (mIsCheater) {
        messageResId = R.string.judgment_toast;
    } else {

    if (userPressedTrue == answerIsTrue) {
        messageResId = R.string.correct_toast;
    } else {
        messageResId = R.string.incorrect_toast;
    }
    }

    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT)
        .show();
}


private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private TextView mQuestionTextView;
private Button mCheatButton;

//we want now to create an array of TrueFalse objects and an index for the array

private TrueFalse[] mQuestionBank = new TrueFalse[] { //we have a question bank
        new TrueFalse(R.string.question_oceans, true), //this is the correct answer
        new TrueFalse(R.string.question_mideast, false), //(true or false) to the question
        new TrueFalse(R.string.question_africa, false),
        new TrueFalse(R.string.question_americas, true),
        new TrueFalse(R.string.question_asia, true),
    };
		private int mCurrentIndex = 0;    	
	    private boolean mIsCheater;

	    @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	        if (data == null) {
	          return;
	        }
	        mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN, false);
	    }   		
		



@Override
protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	//Called when the activity is starting.
	
	
	Log.d(TAG, "onCreate(Bundle) called");
	setContentView(R.layout.activity_quiz);
	//m is a prefix for a field
	//we need to get a reference for the TextView and set its text to the question at the current index
    mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
   // int question = mQuestionBank[mCurrentIndex].getQuestion();
   // mQuestionTextView.setText(question);

	
	// we need to cas the returned view to button before assigning it
	mTrueButton = (Button) findViewById(R.id.true_button);
	mTrueButton.setOnClickListener(new View.OnClickListener() {
				
		@Override
		public void onClick(View arg0) {
			//Toast.makeText(QuizActivity.this, R.string.incorrect_toast, Toast.LENGTH_SHORT).show();
			checkAnswer(true);
			
		}
	});
	
	mFalseButton = (Button) findViewById(R.id.false_button);
	mFalseButton.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			//Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT).show();
			checkAnswer(false);
		}
	});
	
    mNextButton = (Button)findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        	//this listener will increment the index and update the TextView's text
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            mIsCheater = false;
           // int question = mQuestionBank[mCurrentIndex].getQuestion();
           // mQuestionTextView.setText(question);
            // we will put this 2 lines of code into a updateQuestion() method 
            updateQuestion();
            
        }
    });
    if (savedInstanceState != null) {
        mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
    }
    mCheatButton = (Button)findViewById(R.id.cheat_button);
    mCheatButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        	Intent i = new Intent(QuizActivity.this, CheatActivity.class);
        	//putting an extra on the intent
        	boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
            i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
            //modify mCheatButton’s listener to call startActivityForResult(Intent, int).
            startActivityForResult(i, 0);
        }
    });

    updateQuestion(); //we can put this were it was before also (beggining)
}

   @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        Log.i(TAG, "onSaveInstanceState");
        savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
    }
   
@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart() called");
}

@Override
public void onPause() {
    super.onPause();
    Log.d(TAG, "onPause() called");
}

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume() called");
}

@Override
public void onStop() {
    super.onStop();
    Log.d(TAG, "onStop() called");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy() called");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.quiz, menu);
	return true;
}

}
[/code]

CheatActivity.java

[code]package com.example.geoquiz;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class CheatActivity extends Activity {

//Add an implementation of onCreate(…) that passes the resource ID of the layout 
//defined in activity_cheat.xml to setContentView(…).
//In CheatActivity.java, add a key for the extra.
 public static final String EXTRA_ANSWER_IS_TRUE =
		 "com.example.geoquiz.answer_is_true";
  public static final String EXTRA_ANSWER_SHOWN =
	        "com.example.geoquiz.answer_shown";

 private boolean mAnswerIsTrue;
 private TextView mAnswerTextView;
 private Button mShowAnswer;
 
 //add a constant for the extra’s key and a private method that creates 
 //an intent, puts an extra on it, and sets a result. Then call this method in 
 //the Show Answer button’s listener.
 
    private void setAnswerShownResult(boolean isAnswerShown) {
        Intent data = new Intent();
        data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
        setResult(RESULT_OK, data);
    }
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cheat);
    //In CheatActivity, retrieve the value from the extra and store it in a member variable.
    mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
    //wire up the answer textview and the showanswer button to use the retrieved value
    mShowAnswer = (Button)findViewById(R.id.showAnswerButton);
    // Answer will not be shown until the user
    // presses the button
    setAnswerShownResult(false);
    mShowAnswer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mAnswerIsTrue) {
                mAnswerTextView.setText(R.string.true_button);
            } else {
                mAnswerTextView.setText(R.string.false_button);
            }
            setAnswerShownResult(true);
        }
    });
}

}

//The simplest way one activity can start another is with the Activity method
//public void startActivity(Intent intent)

[/code]

this is what log cat shows:

11-09 12:46:39.445: D/QuizActivity(14463): onCreate(Bundle) called 11-09 12:46:39.505: D/QuizActivity(14463): onStart() called 11-09 12:46:39.505: D/QuizActivity(14463): onResume() called 11-09 12:46:39.545: D/libEGL(14463): loaded /system/lib/egl/libEGL_adreno200.so 11-09 12:46:39.545: D/libEGL(14463): loaded /system/lib/egl/libGLESv1_CM_adreno200.so 11-09 12:46:39.555: D/libEGL(14463): loaded /system/lib/egl/libGLESv2_adreno200.so 11-09 12:46:39.555: I/Adreno200-EGL(14463): <qeglDrvAPI_eglInitialize:265>: EGL 1.4 QUALCOMM Build: Iabe52cfaeae4c5fab1acacfe6f056ba15fa93274 11-09 12:46:39.605: D/OpenGLRenderer(14463): Enabling debug mode 0 11-09 12:46:41.387: D/QuizActivity(14463): onPause() called 11-09 12:46:41.847: I/QuizActivity(14463): onSaveInstanceState 11-09 12:46:41.847: D/QuizActivity(14463): onStop() called 11-09 12:46:42.358: D/AndroidRuntime(14463): Shutting down VM 11-09 12:46:42.358: W/dalvikvm(14463): threadid=1: thread exiting with uncaught exception (group=0x41c9b700) 11-09 12:46:42.358: E/AndroidRuntime(14463): FATAL EXCEPTION: main 11-09 12:46:42.358: E/AndroidRuntime(14463): java.lang.NullPointerException 11-09 12:46:42.358: E/AndroidRuntime(14463): at com.example.geoquiz.CheatActivity$1.onClick(CheatActivity.java:50) 11-09 12:46:42.358: E/AndroidRuntime(14463): at android.view.View.performClick(View.java:4240) 11-09 12:46:42.358: E/AndroidRuntime(14463): at android.view.View$PerformClick.run(View.java:17721) 11-09 12:46:42.358: E/AndroidRuntime(14463): at android.os.Handler.handleCallback(Handler.java:730) 11-09 12:46:42.358: E/AndroidRuntime(14463): at android.os.Handler.dispatchMessage(Handler.java:92) 11-09 12:46:42.358: E/AndroidRuntime(14463): at android.os.Looper.loop(Looper.java:137) 11-09 12:46:42.358: E/AndroidRuntime(14463): at android.app.ActivityThread.main(ActivityThread.java:5103) 11-09 12:46:42.358: E/AndroidRuntime(14463): at java.lang.reflect.Method.invokeNative(Native Method) 11-09 12:46:42.358: E/AndroidRuntime(14463): at java.lang.reflect.Method.invoke(Method.java:525) 11-09 12:46:42.358: E/AndroidRuntime(14463): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 11-09 12:46:42.358: E/AndroidRuntime(14463): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 11-09 12:46:42.358: E/AndroidRuntime(14463): at dalvik.system.NativeStart.main(Native Method) 11-09 12:46:46.332: I/Process(14463): Sending signal. PID: 14463 SIG: 9 11-09 12:46:46.452: D/QuizActivity(14714): onCreate(Bundle) called 11-09 12:46:46.482: D/QuizActivity(14714): onStart() called 11-09 12:46:46.482: D/QuizActivity(14714): onResume() called 11-09 12:46:46.522: D/libEGL(14714): loaded /system/lib/egl/libEGL_adreno200.so 11-09 12:46:46.532: D/libEGL(14714): loaded /system/lib/egl/libGLESv1_CM_adreno200.so 11-09 12:46:46.532: D/libEGL(14714): loaded /system/lib/egl/libGLESv2_adreno200.so 11-09 12:46:46.532: I/Adreno200-EGL(14714): <qeglDrvAPI_eglInitialize:265>: EGL 1.4 QUALCOMM Build: Iabe52cfaeae4c5fab1acacfe6f056ba15fa93274 11-09 12:46:46.562: D/OpenGLRenderer(14714): Enabling debug mode 0


#2

Hey blinketo,

You’re trying to use your mAnswerTextView at line 50 before you’ve initialized it from your layout file.

Add:

after you set up mShowAnswer.

Cheers,
Paul.