I am working on a quiz app that involves two activities: a QuizActivity
that displays a list of Question
s, and a QuestionActivity
that displays the details of the question (prompt, options, etc.). In the QuizActivity
I used the startActivityForResult(Intent, int)
method to open the QuestionActivity
, like so:
Intent questionIntent = new Intent(QuizActivity.this, QuestionActivity.class);
questionIntent.putExtra("currentQuestion", currentQuestion);
startActivityForResult(questionIntent, REQUEST_CODE_SELECTED_OPTION);
where REQUEST_CODE_SELECTED_OPTION
is a constant set to 1.
After QuestionActivity
finishes, it should return the index of the selected option (assuming it's a multiple choice question) so I overrode the onPause()
callback:
@Override
public void onPause() {
super.onPause();
Intent returnIntent = new Intent(QuestionActivity.this, QuizActivity.class);
if (curQuestion.selected()) {
returnIntent.putExtra("Result Code", RESULT_OK);
setResult(Activity.RESULT_OK, returnIntent);
Log.d("QuestionActivity", "Returned with " + Activity.RESULT_OK);
} else {
returnIntent.putExtra("Result Code", RESULT_CANCELED);
setResult(Activity.RESULT_CANCELED, returnIntent);
Log.d("QuestionActivity", "Returned with " + Activity.RESULT_CANCELED);
}
}
I have also implemented the onActivityResult(int, int, Intent)
callback in my QuizActivity
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("QuizActivity", "Received result code: " + resultCode);
Log.d("QuizActivity", "Result code from intent: " + data.getIntExtra("Result Code", 100));
if (requestCode == REQUEST_CODE_SELECTED_OPTION) {
if(resultCode == Activity.RESULT_OK){
Log.d("QuizActivity", "Got RESULT_OK");
}
if (resultCode == Activity.RESULT_CANCELED) {
// do nothing
}
}
}
However, when I ran the app, entered QuestionActivity
, selected an option, hit Back, from the log I see that in QuestionActivity
the result code is correctly set to -1:
D/QuestionActivity: Returned with -1
D/QuizActivity: Received result code: 0
but in the onActivityResult(int, int, Intent)
method the result code is 0. In addition, I also tried putting an int
in the intent being passed back, but in QuizActivity
the received intent is null
. I am really confused. Am I using the methods wrong?