How to return values of a daughter Activity in Kotlin

Asked

Viewed 248 times

1

Hello, I’m starting to work with Kotlin and I have the following situation:

  • I have the Activity Foo with a button that navigates to Activity Bar.
  • In Bar, I process some information and have a button to go back.
  • When returning, I must return this processed information to Foo

I wonder if there is already some standard implemented to do this in Kotlin (Android) so I can learn already using best practices...

Note: at first I thought of having a Viewmodel implanted in Foo and try to pass on to Bar the instance of the same, but it seemed to me a little bit "forced" so I came to clarify better the "how to do"

  • 1

    The "canonical" way would be to use Intents, personally I prefer to use Sharedpreferences, activity B modifies a value in the application’s Shared preferences, and activity A is the Preference Change System. The use of a shared Singleton among the various activities, perhaps residing in a static class, is also valid.

  • 1

    I would say that the title of the question is not very clear, because it gives the idea of inheritance between the Activities, when in the example Foo and Bar are distinct and do not share any relationship of inheritance

  • So I think if I take and use a VM that can be passed to the second is valid because it would work as a correct Singleton?

2 answers

1


the class Foo must, in addition to creating the Intent, have a reference constant for the startActivityForResult function call:

val intent = Intent(this, Bar::class.java)
startActivityForResult(intent, REQUEST_CODE)

companion object{
    private const val REQUEST_CODE = 123
}

in class Bar, you will also need a reference variable for Activity that called to know if the data that is coming is really what you requested.

fun whenDataIsReady(){
   val intent = Intent()
   intent.putExtras("key", "value")
   setResult(RESULT_CODE, intent)
   finish()
}

companion object{
    const val RESULT_CODE = 111
}

Back to Foo, in the onActivityResult function you must check whether the request code was requested by Foo and whether the result code was returned by Bar

fun onActivityResult(requestCode: Int,resultCode: Int,data: Intent) {
    if(requestCode == REQUEST_CODE && resultCode == RESULT_CODE){
        //trate os dados que chegaram da intent
    }
}

0

Hello, you should use Onactivityresult to retrieve the data:

You start the Bar like this:

Intent(this,Bar::class.java);
        startActivityForResult(intent , REQUEST_CODE);

In the Bar class when the Butão is pressed back:

 val intent = getIntent();
   intent.putExtra("chave", valor);
   setResult(RESULT_OK, intent);
   finish();

And then you get the value in the Foo class:

 fun onActivityResult(int requestCode, int resultCode, Intent data) {
      }

Browser other questions tagged

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