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

55 Views Asked by At

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?

3

There are 3 best solutions below

0
Driexus On BEST ANSWER

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.

0
Pietrek On

use var yourVariable in Activity and read/set it with getActivity().yourVariable in fragment

0
Dhruv Limbachiya On

You can use interfaces to pass data from fragment to its parent activity.

Here's an example

  1. Create an Interface: Define an interface in your fragment that the activity will implement.

    interface DataPassListener {
       fun onDataPassed(data: String) 
    }
    
    class MyFragment : Fragment() {
       private var dataPassListener: DataPassListener? = null
    
    // Rest of your fragment code
    
    // Call this method when you want to pass data to the activity
      private fun passDataToActivity(data: String) {
         dataPassListener?.onDataPassed(data)
      }
    }
    
  2. Implement the Interface in the Activity: Implement the interface in your activity and override the onDataPassed method.

    class MyActivity : AppCompatActivity(), DataPassListener {
    
    // Other activity code
    
      override fun onDataPassed(data: String) {
        // Handle the passed data in the activity
        // You can perform any actions with the received data here
      }
    }
    
  3. Set the Interface in the Fragment: In the onAttach method of your fragment, set the dataPassListener with the activity context. Also, make sure to detach the listener in the onDetach method.

    class MyFragment : Fragment() {
      private var dataPassListener: DataPassListener? = null
    
      override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is DataPassListener) {
            dataPassListener = context
        } else {
            throw ClassCastException("$context must implement DataPassListener")
        }
    }
    
    override fun onDetach() {
        super.onDetach()
        dataPassListener = null
    }
    
    // Rest of your fragment code
    
    // Call this method when you want to pass data to the activity
    private fun passDataToActivity(data: String) {
        dataPassListener?.onDataPassed(data)
      }
    }
    
  4. Pass Data from Fragment to Activity: Now, you can call the passDataToActivity method in your fragment whenever you want to send data to the activity.

    class MyFragment : Fragment() {
    
    // Other fragment code
    
      private fun someFunction() {
        val dataToSend = "Hello, Activity!"
        passDataToActivity(dataToSend)
      }
    }
    

This way, your activity will receive the data through the onDataPassed method whenever the fragment calls passDataToActivity