aminakoy
aminakoy

Reputation: 423

Passing a Custom Type Object From Fragment to Activity with Navigation Component

I wanted to pass a MediaStream object within a Fragment to an Activity using the Navigation Component. The MediaStream class belongs to WebRTC. So, I could not touch it to make it parcelable or serializable for passing the object around.

Here is the code from the fragment:

// Creating a PeerConnection with two callbacks 
// one is triggered when an ICE candidate is received
// the other one is triggered when a MediaStream is received
localPeer = peerConnectionFactory.createPeerConnection(
            rtcConfig,
            object: CustomPeerConnectionObserver("localPeerCreation"){
                override fun onIceCandidate(iceCandidate: IceCandidate?) {
                   // not relevant for this talk 
                }

                override fun onAddStream(mediaStream: MediaStream?) {
                    super.onAddStream(mediaStream)
                    // TODO: create a new Activity and pass media stream to it for displaying
                    StreamsFragmentDirections.actionStreamsFragmentToStreamActivity(mediaStream)
                }
            })!!

As the TODO line implies, my initial goal was to pass the MediaStream object to a new Activity which should display the stream. But I did not know how to do it. In the Navigation Graph Editor, I selected <inferred type> as type for mediastream but that not worked out as expected. Here, the relevant part from the navigation graph xml layout:

<activity
        android:id="@+id/streamActivity"
        android:name="com.john.elia.ui.activities.StreamActivity"
        android:label="StreamActivity" >
        <argument 
            android:name="mediaStream" />
</activity>

But the compiler complains, saying that it expected an Int but found a MediaStream. How can I pass the MediaStream object ? In all the examples I have found they only show how to pass primitive types like a String, Int etc. How about objects with custom types?

Upvotes: 1

Views: 2744

Answers (1)

B&#246; macht Blau
B&#246; macht Blau

Reputation: 13009

You may not be able to make every type of object implement Parcelable, but by following the principles of modern app architecture, you don't have to do so any more, see also the Guide to app architecture

The general idea is to have your data in a repository (the single source of truth) which can be accessed by Activitys and Fragments via some custom class extending ViewModel.

So once you obtain any type of data (the MediaStream) in the Fragment, you should pass it to the repository, navigate to the next UI component and have it fetch the data from the repository with the help of its own ViewModel.

Upvotes: 2

Related Questions