Search code examples
androidstringandroid-fragmentsandroid-intentandroid-activity

After passing a string to my Activity, trying to get it in a fragment results in an empty string


I pass a String via intent like this:

val intent = Intent(this, RegistrationActivity::class.java)
        intent.putExtra("mobile", user.mobile)
        startActivity(intent)

Then I successfully receive this in my RegistrationActivity.

private var mobile : String? = ""
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_registration_layout)

    val intent = this.intent
    val extras = intent.extras
    mobile = extras?.getString("mobile")
    }

fun getMobile(): String {
    return mobile!!
}

but then when I call getMobile() in a fragment that lives in the RegistrationActivity, all I get is an empty string:

val activity = RegistrationActivity()
val mobile = activity.getMobile()

Solution

  • Don't create an instance of activity like that, use startActivity() to navigate to activity, it will create an instance of it. check Activity lifecycle

    since you created an instance of the activity in the wrong way, the onCreate() won't call and mobile will be the initial value.

    here is an example of how you can access activity from fragment:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    
        val mobile = (activity as? RegistrationActivity)?.getMobile()
    }