Home > database >  How does this method of passing data from Activity to Fragment via interface work under the hood?
How does this method of passing data from Activity to Fragment via interface work under the hood?

Time:06-02

I am passing some data from my Activity to my DialogFragment using this interface and I want to better understand why this works. It seems as if the activity subscribes to the interface and implements the methods defined in it, returning the strings to the interface. Then the DialogFragment declares an instance of the interface and grabs the data that was stored there from the Activity. Is my understanding correct or is there a better or more complete way of describing what is going on?

Here is my code:

interface ResultReceiver {

    fun getSerialNumber(): String

    fun getDevicePassword(): String

    fun getMacAddress(): String

    fun getDevice(): BluetoothDevice
}

I am subscribing to the interface in my activity and setting the data like so:

class ScannerActivity: AppCompatActivity(), ResultReceiver {

    private lateinit var serialNumber: String
    private lateinit var devicePassword: String    
    private lateinit var device: BluetoothDevice
    private lateinit var macAddress: String


    ...


    override fun getSerialNumber(): String {
        return serialNumber
    }

    override fun getDevicePassword(): String {
        return devicePassword
    }

    override fun getMacAddress(): String {
        return macAddress
    }

    override fun getDevice(): BluetoothDevice {
        return device
    }
}

This is how I get it into my DialogFragment:

private lateinit var resultReceiver: ResultReceiver

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog  {

        resultReceiver = requireContext() as ResultReceiver

        val devicePassword = resultReceiver.getDevicePassword()

        val serialNumber = resultReceiver.getSerialNumber()

        val macAddress = resultReceiver.getMacAddress()


        ...


}

CodePudding user response:

Fragments end up associated with a Context, which is usually an Activity but not necessarily. When you call requireContext() as ResultReceiver you're a) assuming you have a context, and b) it implements the ResultReceiver interface

Since your fragment is hosted in a ScannerActivity, that's what your Context is. And because it implements ResultReceiver, you can cast it as one, and use all the functions in that interface - getDevicePassword() etc. You could show that dialog in other activities too, so long as they also implement ResultReceiver. It's not tied to any one type of parent activity, just something that implements that interface

So you're just talking directly to your activity, through the methods it's required to have as a ResultReceiver, that's all!

  • Related