Skip to content

Migrate ResultsScreen to use Nav3 #95

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

srikrishnasakunia
Copy link

@srikrishnasakunia srikrishnasakunia commented Aug 11, 2025

Addresses #88

…vigation.kt using Nav3 instead of driving them from CreationScreen.kt

# Conflicts:
#	feature/results/src/main/java/com/android/developers/androidify/customize/ImageRenderer.kt
This commit refactors image handling in the `CreationViewModel` and `CustomizeExportViewModel`.

**CreationViewModel:**
- The `saveBitmapToCache` function has been removed.
- Image saving is now delegated to `imageGenerationRepository.saveImage(bitmap)`.

**CustomizeExportViewModel:**
- Images are now loaded from a URI using a new `convertUriToBitmap(uri)` suspend function. This function uses the `application.contentResolver` to open an input stream from the URI and decodes it into a Bitmap.
- The `export()` function was updated to use `convertUriToBitmap` to get the image for export instead of directly accessing `state.value.exportImageCanvas.imageBitmap`.
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @srikrishnasakunia, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

I've undertaken a significant refactoring effort to enhance the application's image handling and navigation. The primary goal was to move away from directly passing large Bitmap objects between screens, which can be inefficient and lead to memory issues. Instead, I've implemented a system that utilizes Android's Uri (Uniform Resource Identifier) for image results. This change not only improves memory management but also streamlines the overall navigation flow from image creation to the display of results and subsequent customization, making the application more robust and performant.

Highlights

  • Image Handling Refactor: I've refactored the application's image handling to switch from passing Bitmap objects directly to using Uri objects for image results across the application. This change impacts the CreationViewModel, ResultsScreen, and CustomizeAndExportScreen, improving memory management and enabling better integration with Android's content URI system.
  • Navigation Flow Update: I've introduced new ImageResult and ShareResult navigation routes in NavigationRoutes.kt. These routes are now used to manage the flow from image creation to result display and customization, ensuring that image data is passed efficiently using Uris.
  • Decoupling UI from Bitmap: I've removed direct Bitmap references from UI composables and ViewModels in the 'feature/results' and 'feature/creation' modules, replacing them with Uris. Bitmaps are now loaded from Uris only when explicitly needed for display or processing, which helps in decoupling the UI from heavy image data.
  • Streamlined Creation to Results Transition: The CreationScreen now utilizes an 'onImageCreated' callback to trigger navigation to the ResultsScreen with the generated image's Uri. This streamlines the transition, eliminating the need for CreationScreen to directly manage the states of ResultsScreen and CustomizeAndExportScreen.
  • Test Updates: Corresponding unit and instrumentation tests across the application have been updated to reflect the change from Bitmap to Uri for image handling, ensuring continued correctness and stability of the features.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request implements the results screen and integrates it into the navigation flow using navigation3. The changes involve passing image data as URIs instead of Bitmaps, which is a great improvement for performance and stability. The navigation logic has been updated to include the new screens, and feature modules have been decoupled from navigation concerns. I've found a critical issue in the navigation logic that could lead to an incorrect back stack, and a high-severity issue regarding a potential resource leak. Other suggestions are minor improvements to code clarity and best practices.

Comment on lines +116 to +125
onImageCreated = { resultImageUri, prompt, originalImageUri ->
backStack.removeAll{ it is ImageResult}
backStack.add(
ImageResult(
result = resultImageUri.toString(),
prompt = prompt,
originalImageUri = originalImageUri?.toString()
)
)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The current implementation of onImageCreated adds the ImageResult screen on top of the Create screen in the back stack. This leads to an incorrect navigation flow when pressing the back button from the results screen, as it would create a stack of Create screens ([..., Create, Create]).

To fix this, you should replace the Create screen with the ImageResult screen in the back stack. This ensures that navigating back from the results screen correctly returns the user to a single, updated creation screen.

                    onImageCreated = { resultImageUri, prompt, originalImageUri ->
                        backStack.removeAll { it is ImageResult }
                        // Replace the current entry (Create) with ImageResult to ensure a correct back stack
                        if (backStack.isNotEmpty()) {
                            backStack[backStack.lastIndex] = ImageResult(
                                result = resultImageUri.toString(),
                                prompt = prompt,
                                originalImageUri = originalImageUri?.toString()
                            )
                        } else {
                            backStack.add(
                                ImageResult(
                                    result = resultImageUri.toString(),
                                    prompt = prompt,
                                    originalImageUri = originalImageUri?.toString()
                                )
                            )
                        }
                    }

originalImageUrl: Uri?,
) {
_state.update {
CustomizeExportState(
originalImageUrl,
exportImageCanvas = it.exportImageCanvas.copy(imageBitmap = resultImageUrl),
exportImageCanvas = it.exportImageCanvas.copy(imageUri = resultImageUrl),
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think this is where its losing state on restoring from background. we can keep the imageUri, but we should probably add the loaded image to the State to be able to draw it.
So instead of changing the imageBitmap to imageUri, lets add an imageUri parameter, and then on load of the bitmap, we set the state to that Bitmap.

When it comes back from being in the background, we will need to rehydrate the state to load up the bitmap again.

Comment on lines 216 to +224
ScreenState.RESULT -> {
val prompt = uiState.descriptionText.text.toString()
val key = if (uiState.descriptionText.text.isBlank()) {
uiState.imageUri.toString()
} else {
prompt
}
ResultsScreen(
uiState.resultBitmap!!,
onImageCreated(
uiState.resultBitmapUri!!,
uiState.descriptionText.text.toString(),
if (uiState.selectedPromptOption == PromptType.PHOTO) {
uiState.imageUri
} else {
null
},
promptText = prompt,
viewModel = hiltViewModel(key = key),
onAboutPress = onAboutPressed,
onBackPress = onBackPressed,
onNextPress = creationViewModel::customizeExportClicked,
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

We should likely be able to remove this state now as the Result screen state is handled by Nav3

Copy link
Collaborator

Choose a reason for hiding this comment

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

So we should only have here, Edit and Loading.

Comment on lines +107 to 109
LaunchedEffect(resultImageUri, originalImageUri) {
viewModel.setArguments(resultImageUri, originalImageUri)
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

@dturner may have some more suggestions here for setting the arguments on the ViewModel, at the time when we were implementing Nav3 there wasn't easy support for Arguments, I think there may be support for nav arguments now with SavedStateHandle. That should help handle the rehydration of the ViewModel too.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes, you can use the factory pattern to provide the route to the ViewModel when it's created. See example here: https://github.com/android/nav3-recipes/blob/main/app/src/main/java/com/example/nav3recipes/passingarguments/injectedviewmodels/InjectedViewModelsActivity.kt#L93.

This avoids the need for LaunchedEffect.

},
onBackPress = {
backStack.removeLastOrNull()
backStack.add(Create(fileName = resultKey.originalImageUri, prompt = resultKey.prompt))
Copy link
Collaborator

Choose a reason for hiding this comment

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

As far as I understand, we shouldn't need to do this as the Create() entry should already be on the backstack after removing the last one?

Copy link
Collaborator

@riggaroo riggaroo left a comment

Choose a reason for hiding this comment

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

Getting there! left some comments.

Copy link
Contributor

@dturner dturner left a comment

Choose a reason for hiding this comment

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

Took an initial pass

ResultsScreen(
uiState.resultBitmap!!,
onImageCreated(
uiState.resultBitmapUri!!,
Copy link
Contributor

Choose a reason for hiding this comment

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

Use of !! is strongly discouraged. Either resultBitmapUri cannot be null or it can and the null case should be handled.

@riggaroo riggaroo changed the title Krishna/nav3 result screen imp Migrate ResultsScreen to use Nav3 Aug 13, 2025
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.

3 participants