Linking Presenter with View (Fragment)
https://github.com/googlesamples/android-architecture/blob/30f7c5a16bb0854e003530e81403e922e745d311/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/addedittask/AddEditTaskActivity.java#L86
Please do correct me if I am wrong, but isn't this approach as bad as creating a Fragment with argument constructor?
Although, the above implementation would work fine, since we are linking the presenter to the fragment in onCreate() method of the Activity, which will surely get called whenever the system kills and later recreates my activity instance.
But consider this scenario: Suppose I am adding a fragment to my screen on some button click. If Android then decides to kill my fragment, and later recreates it using a no-arg constructor call, then there won't be any presenter attached to the fragment if I have linked it with this approach, is this correct?
Yes, you're absolutely right to question the approach used in the AddEditTaskActivity from the android-architecture sample, especially with regard to presenter-linking in Fragments.
Let’s break it down:
What the sample does: In AddEditTaskActivity, the presenter is created and passed to the fragment like this:
AddEditTaskFragment fragment = AddEditTaskFragment.newInstance(); presenter = new AddEditTaskPresenter(...); fragment.setPresenter(presenter); This is done inside the onCreate() of the Activity. So everything works fine when the Activity and Fragment are recreated together, such as after a configuration change.
The problem you're raising: If the Fragment is re-added dynamically (e.g., via a button click), and later Android kills only the Fragment (e.g., due to memory pressure), it will recreate it using the no-argument constructor and restore state via the FragmentManager.
At that point:
The setPresenter() method is never called again, unless explicitly handled.
So yes, your Fragment would be missing the Presenter, and this would cause a crash or empty view behavior.
Correct observation: "...this approach is as bad as creating a Fragment with an argument constructor"
Yes, this is equally fragile, since both:
Rely on manual reconstruction
Violate the principle of Fragment recreation via no-arg constructor + saved state
Solution/Best Practice: Use Fragment’s onAttach() to rebind the Presenter if possible.
Inject the presenter via Dependency Injection (like Dagger/Hilt) or a shared ViewModel.
Avoid calling setPresenter() manually from Activity unless:
You're 100% sure both are created and destroyed together.
Alternative approaches:
Store the Presenter in a ViewModel scoped to the activity (if using MVVM).
Use setRetainInstance(true) if using MVP and you want to keep Presenter alive across config changes.
Reconstruct Presenter using saved arguments in Fragment's onCreate():
presenter = new AddEditTaskPresenter(...);