Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Draw area task] Fix crashes on config change #2761

Merged
merged 24 commits into from
Oct 2, 2024

Conversation

gino-m
Copy link
Collaborator

@gino-m gino-m commented Sep 23, 2024

  • Instead of passing the view model in constructor, this PR gets the vm from the parent fragment.
  • The task ID is passed as an arg to the child fragment so that it knows which view model to request from its parent.
  • The camera move handler requires the map to be initialized, so the collect call is moved to after the map has loaded.
  • Uses an injected Provider to create new instances so that @Inject works.
  • Reinitialize DataCollectionViewModel on config changes so that view is restored.

Fixes #2725
Towards #2624, #2682

Screen_recording_20240918_224809.webm

The data collection flow still reverts to the previous step in the flow on config change, and exits if in the first position, but this is likely an unrelated issue.

@gino-m gino-m marked this pull request as ready for review September 23, 2024 21:21
@gino-m
Copy link
Collaborator Author

gino-m commented Sep 23, 2024

Config changes are now supported on DrawAreaTask:

Screen_recording_20240923_172230.webm

Unsaved draft Changes are still restored when the app is killed:

Screen_recording_20240923_172342.webm

@anandwana001 would you like to apply a similar fix to remaining Task(Map)Fragments?

@@ -95,6 +96,8 @@ abstract class BaseTaskFragmentTest<F : AbstractTaskFragment<VM>, VM : AbstractT
preTransactionAction = {
fragment = this as F
fragment.taskId = task.id
// TODO: Attach `fragment` to mock DataCollectionFragment
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@shobhitagarwal1612 @anandwana001 DrawAreaTaskFragmentTest is failing with:

Fragment DrawAreaTaskMapFragment{44fdc5b3} (07ec492d-1efe-474f-94ab-b361fdc1063e id=0x2c93 tag=DrawAreaTaskMapFragment) is not a child Fragment, it is directly attached to dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper@33500213
java.lang.IllegalStateException: Fragment DrawAreaTaskMapFragment{44fdc5b3} (07ec492d-1efe-474f-94ab-b361fdc1063e id=0x2c93 tag=DrawAreaTaskMapFragment) is not a child Fragment, it is directly attached to dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper@33500213
	at androidx.fragment.app.Fragment.requireParentFragment(Fragment.java:1183)
...

I believe we have to update the way we mock out the task view model here, but not sure how. Any ideas?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resharing @anandwana001 's suggestion via chat:

adding childfragment:

inline fun <reified T : Fragment> launchFragmentWithNavController(
  fragmentArgs: Bundle? = null,
  @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme,
  destId: Int,
  fragment: Fragment?=null,
  crossinline preTransactionAction: Fragment.() -> Unit = {},
  crossinline postTransactionAction: Fragment.() -> Unit = {},
): ActivityScenario<HiltTestActivity> =
  hiltActivityScenario(themeResId).launchFragment<T>(
    fragmentArgs,
    {
      // Attach `fragment` as a child of the mock `DataCollectionFragment`
      parentFragment?.childFragmentManager?.beginTransaction()
        ?.add(R.id.data_collection_fragment, fragment!!, "childFragmentTag")
        ?.commitNow()

      this.preTransactionAction()
      viewLifecycleOwnerLiveData.observeForever { viewLifecycleOwner ->
        if (viewLifecycleOwner != null) {
          val navController = TestNavHostController(getApplicationContext())
          navController.setViewModelStore(ViewModelStore())
          // Required for graph scoped view models.
          navController.setGraph(R.navigation.nav_graph)
          navController.setCurrentDestination(destId, fragmentArgs ?: bundleOf())

          // Bind the controller after the view is created but before onViewCreated is called.
          Navigation.setViewNavController(requireView(), navController)
        }
      }
    },
  ) {
    this.postTransactionAction()
  }

and pass the parent fragment

launchFragmentWithNavController<T>(
  destId = R.id.data_collection_fragment,
  fragment = DataCollectionFragment(),
  preTransactionAction = {
    // Set up fragment-specific properties
    fragment = this as F
    fragment.taskId = [task.id](http://task.id/)
  }
)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@shobhitagarwal1612 Any ideas on the best way to create and attach DataCollectionFragment as the parent to the task under test here? We need to get the view model used by the tasks.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@shobhitagarwal1612 Gentle ping

mapViewModel = getViewModel(BaseMapViewModel::class.java)
val taskId = arguments?.getString(TASK_ID_ARG_KEY) ?: error("null taskId arg")
val dcf = requireParentFragment() as DataCollectionFragment
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

requireParentFragment() can throw an exception, can we handle it?

This is the edge case, if this fails, no ViewModel will be there

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can that ever happen in practice, and is it something we can recover from?

@@ -57,7 +64,6 @@ class DrawAreaTaskMapFragment(private val viewModel: DrawAreaTaskViewModel) :
}

companion object {
fun newInstance(viewModel: DrawAreaTaskViewModel, map: MapFragment) =
DrawAreaTaskMapFragment(viewModel).apply { this.map = map }
const val TASK_ID_ARG_KEY = "taskId"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AbstractTaskFragment already has this, how about using the same rather than creating this new?

Copy link
Collaborator Author

@gino-m gino-m Sep 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AbstractTaskFragment has the key used in Bundle, not Fragment args. They happen to have the same value, but that can be considered coincidental.

Copy link

codecov bot commented Oct 2, 2024

Codecov Report

Attention: Patch coverage is 69.23077% with 8 lines in your changes missing coverage. Please review.

Project coverage is 60.86%. Comparing base (ba72a46) to head (2be5c19).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...ollection/tasks/polygon/DrawAreaTaskMapFragment.kt 42.85% 4 Missing ⚠️
...tacollection/tasks/polygon/DrawAreaTaskFragment.kt 66.66% 0 Missing and 2 partials ⚠️
...ain/java/com/google/android/ground/MainActivity.kt 0.00% 0 Missing and 1 partial ⚠️
...ground/ui/datacollection/DataCollectionFragment.kt 80.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #2761      +/-   ##
============================================
- Coverage     60.93%   60.86%   -0.07%     
- Complexity     1158     1159       +1     
============================================
  Files           265      265              
  Lines          6141     6146       +5     
  Branches        854      856       +2     
============================================
- Hits           3742     3741       -1     
- Misses         1916     1921       +5     
- Partials        483      484       +1     
Files with missing lines Coverage Δ
...in/java/com/google/android/ground/MainViewModel.kt 77.77% <100.00%> (+1.03%) ⬆️
...round/ui/datacollection/DataCollectionViewModel.kt 71.93% <100.00%> (-0.97%) ⬇️
...ain/java/com/google/android/ground/MainActivity.kt 36.26% <0.00%> (ø)
...ground/ui/datacollection/DataCollectionFragment.kt 56.12% <80.00%> (+0.33%) ⬆️
...tacollection/tasks/polygon/DrawAreaTaskFragment.kt 59.25% <66.66%> (+0.43%) ⬆️
...ollection/tasks/polygon/DrawAreaTaskMapFragment.kt 27.27% <42.85%> (-6.07%) ⬇️

@gino-m gino-m merged commit 92c5392 into master Oct 2, 2024
2 checks passed
@gino-m gino-m deleted the gino-m/2725/fix-task-constructors branch October 2, 2024 17:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

0.1.9-Openforis DrawAreaTaskMapFragment App Crash
3 participants