Search code examples
androidkotlinandroid-activityfragment

How can I use value in Fragment from parent Activity or other Activities?


I'm trying to deliver value in Fragment to its parent Activity (Parent Activity means Fragment's Parent Activity: Fragment is in Parent Activity)

I know I can use ShareViewModel, but I want to know how can I solve this issue using Bundle or Intent object.

if (findIdAsync(name, number) != null) {
        id = findIdAsync(name, number).toString()
} else {
    id = ""
}

findIdAsync method returns id if there is a process, if not it'll return an empty string "".

How can I pass the id value to its parent Activity?


Solution

  • The correct way in my opinion is to use a ViewModel as you mentioned. Neither bundles nor intents are useful for your issue as their purpose is completely different.

    Although bundles are used to pass data between fragments or activities, you cannot control the moment the data is retrieved, as you can only retrieve it in core lifecycle methods like onCreateView:

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val intFromBundle = savedInstanceState?.getInt("MY_INT_KEY")
        ...
    }
    

    Intents are not useful for your issue either. From the docs:

    An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities.

    You can read more about preserving ui states here.