android / android/architecture-samples
[todo-mvp-dagger] Fragments get constructed twice every time an Activity is restored
- Dominant language
- Kotlin
- Stars
- 45.8k
- Forks
- 11.9k
- PR merge metrics
- No merged PRs in 30d
Description
The code currently `@Inject`s the `StatisticsFragment` in [`StatisticsActivity`](https://github.com/googlesamples/android-architecture/blob/97214a30e99f2d22f329d5de05e710960240a99e/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsActivity.java#L42), which can lead to a very confusing situation when the Activity is restored (configuration change, low memory, etc.):
- Dagger creates a new `StatisticsFragment` instance and injects it into the field.
- A new, *different* `StatisticsFragment` instance gets created and attached by `super.onCreate` as part of the restore process.
- The [code](https://github.com/googlesamples/android-architecture/blob/97214a30e99f2d22f329d5de05e710960240a99e/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsActivity.java#L68) detects that the restored fragment already exists, so it doesn't use the Dagger-created `fragment` instance.
- The injected `fragment` field now contains an unused, unattached fragment.
The fact that `StatisticsFragment`'s constructor was called twice is also a problem.
A similar situation can occur with the other activities.
Contributor guide
Research direction
Start with todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsActivity.java, especially the injected fragment field and onCreate restoration path. Reproduce an Activity restoration or configuration change and inspect the other activities for the same pattern; done means restoration does not construct an unused second StatisticsFragment.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- android, java
- Domain
- mobile
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100