How to pass a parameter from an Activity b to Activity A

Asked

Viewed 24 times

0

Good evening, I need help to solve the following problem, I’m doing a Million Dollar Show style game. I have a main activity that is where the questions occur and has the buttons that trigger the aids. When the user clicks on the card button, it opens a second Activity (detail, the main Activity remains open), when generating the letter I need to pass the value of that letter to Main Activity.

The problem is that if I use the code below:

Note: This code is used in Activity 2, which would be a temporary screen that runs a code and goes back to Main Screen

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

intent.putExtras("valor", valor); // value is the attribute I need to pass to main screen.

startActivity(intent);

I’m going to restart the main Activity, and I can’t do that, because I would be missing the progress of the game. So I need to pass this parameter another way.

Detail, I don’t have much experience I’m starting to program on this platform, so who can send a detailed reply thank you.

1 answer

0

You need to use the Activity Result API methods for this. Really, if you call a startActivityForResult in the second Activity, the first Activity will be started from scratch, and is not what you want (inclusive, the animation transition between these screens will also give the impression that you are "going" to this screen instead of "returning").

To do what you want, you need to use another set of methods. Considering that you want to send the ID of the clicked letter (as int) to the second Activity, and that you need to return this "value" as String, you need to define a contract class for this exchange of information between the Activities:

class MyContract : ActivityResultContract<Int, String>() {
    override fun createIntent(context: Context, cardId: Int) =
        Intent(context, SecondActivity::class.java).apply {
            putExtra(CARD_ID_EXTRA, cardId)
        }

    override fun parseResult(resultCode: Int, intent: Intent?): String? {
        if (resultCode != Activity.RESULT_OK) {
            return null
        }

        return intent?.getStringExtra(VALUE_EXTRA)
    }

    companion object {
        const val CARD_ID_EXTRA = "card_id"
        const val VALUE_EXTRA = "valor"
    }
}

This class defines that you will pass an Int and receive a String back. See where Intent is created and how the "value" will be extracted from the return Intent. This will be done implicitly in your main code, because it is already defined here.

Now, in your Mainactivity, create an instance of that contract between the two Activities:

val contractLauncher = registerForActivityResult(MyContract()) { str ->
    // faça o que quiser com str, que é "valor" retornado pela segunda Activity
}

That one contractLauncher will be used to start the second Activity. Then, at the click of the letter button, you will call the following code:

contractLauncher.launch(cardId)

That will create an Intent with that cardId and open the second Activity with it. Everything as already defined in the class MyContract.

Now, in your second Activity, you need to pick up the value of the card:

val cardId = intent.extras?.getInt(MyContract.CARD_ID_EXTRA) ?: -1

The value of cardId will be what was passed there in Mainactivity (or -1, if someone starts this second Activity without passing a pro value cardID).

And yet in this second Activity, the moment the person chooses the "value", you need to do the following to indicate that it is to return him:

setResult(Activity.RESULT_OK, Intent().apply {
    putExtra(MyContract.VALUE_EXTRA, valor)
})
finish()

That one finish() will finish the second Activity and return to Mainactivity (and not start Mainactivity again) and will pass this value back to her. That callback with str set up there, at the time you created the contractLauncher, will be called and you will be able to use this value back in Mainactivity. The transition animation will now be as if you have "gone back" to previous Activity, which is what you want.

See more details on this in the official documentation on: https://developer.android.com/training/basics/intents/result

  • Good morning friend, I thank you for your help. Very enlightening the text. I even managed to solve the problem before your answer. I got two ways. The first I generated the draw of the value to be displayed in the letter and consequently in the deletion of the wrong answers on the main screen. And as she was already making an Index calling the Letters screen, I passed this value as extra and on the letter screen I picked up this value and regardless of the letter the user click the draw had already been set....

  • The second approach I did was to create a method within the Activity Cards to do the draw there, and in the Main Screen Activity I set up the Activity Cards as an object and finished the method by pulling the drawn value. It also worked... but there’s a flaw in both options and I wanted to take advantage of your knowledge to see if I can fix it. When I am running a command pad Ex: When you click on a button it plays a sound, it generates the draw of the value of the cards, it calls Activity Cards where the visual part showing the drawn card would happen...

  • But before calling this Activity Cards it also executes the command that eliminates the wrong options causing the user to see this before the draw of the cards. This command should only be executed after the Activity Cards call is automatically closed as soon as the user chooses the card, then only then would it return to Activity Main Screen and continue the course of the command.

  • I don’t know if I can be clear, but what’s happening in a nutshell is that when I execute a command that should occur in parts, I see everything occurring at once, even if I create a method that generates a Sleep between a command and another within the same code snippet this is not respected, it generates all the code and the Sleep pause only happens after everything runs.

  • Imagine a command that had to show from 0 to 10 having 1 second of time between each. He would generate all the numbers and only at the end he would give the break of 1 second... more or less that! You know how I can solve?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.