Returning value from fragment into parent activity on Android

This post will show you how to return a value set in a dialog fragment back to the parent activity it was called from. Code sample provided here is from the Auto-WOL app I made not so long ago, so if you need the bigger picture, feel free to check TimePickerFragment and DeviceActivity classes over at github. This example uses TimePickerDialog. It also keeps track of the layoutId (where the layout it is bound to acts as a button in the UI) because in my app I have multiple buttons which can invoke the same TimePickerFragment so I needed to know which button invoked the dialog fragment because upon selecting the time the button caption gets updated.


So, to make this whole thing work, we will need a fragment class which will extend DialogFragment and implement TimePickerDialog.OnTimeSetListener. This class will expose the OnTimePickedListener interface so it could later be consumed by the parent activity. This class will also be responsible for registering and calling the callback on time set event. The defined OnTimePickedListener interface has only one method signature – onTimePicked(), which will need to be implemented by the parent activity. Other than this, the class only has a few more overrides and that’s all.

The parent activity class implements the OnTimePickedListener defined in TimePickerFragment. This means we are requried to override the onTimePicked() method. This method is what gets executed after time has been picked in the dialog pop-up and “Done” confirmation button has been pressed. From here you’re back in your activity class and can do whatever you want with the obtained data.