Chapter 6 , method deprecated

Hi , Today I was reading chapter 6 everything works until Listing6.13 Calling startActivityForResult(…)
can anyone please explain what should I do now? I read about it on google documentation but it was too complicated for me as a beginner .

Yes I have been having the same problem for 3 days now. It is too complicated for a beginner to implement something new on his own when he doesn’t even know what it is. Please any help

Actually I have found a solution and I will post the code in a short while

This is to first pass the result from the Child Activity(CheatActivity)

// This sends data back to the parent activity telling if the user checked an answer to any Question
private fun setAnswerShownResult(isAnswerShown:Boolean) {
    val data = Intent().apply {
        putExtra(EXTRA_ANSWER_IS_SHOWN, isAnswerShown)
    }

    // setResult() tells the state of how the child activity ended...
    setResult(Activity.RESULT_OK, data)
}

Then this handles the resullt. This is an ActivityCall back. This is used since startActivityForResult is deprecated

// This passes an activity to the Activity manager to obtain the result of the Activity
private val getResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result →

    // handles the result gotten from the child activity
    if(result.resultCode == RESULT_OK) {
        quizViewModel.isCheater = result.data?.getBooleanExtra(EXTRA_ANSWER_IS_SHOWN, false) ?: false

    } // else -> Activity.RESULT_CANCELLED will automatically be called if Activity.RESULT_OK is not called

}

Then lastly launching the Activity

// This is the cheatButton
cheatButton.setOnClickListener {
val answerIsTrue = quizViewModel.currentQuestionAnswer
val intent = CheatActivity.newIntent(this@MainActivity, answerIsTrue)
getResult.launch(intent)
}

    updateQuestions() // This is added here to so that the first Question will initially appear in the questionsTextView
}

This is the modern day solution

4 Likes

Awesome! Thank you for workaround Dan!

1 Like

No problem. Just helping out :+1:

This is such a nice, succinct answer. Well done, dan.

1 Like

lol I’m just seeing this late now but thank you very much.