Mohammad Derakhshan
Mohammad Derakhshan

Reputation: 1562

how to pass bitmap from a screen to another using jetpack compose navigation

I'm using jetpack compose. I have two screens, and I want to send a Bitmap from the first one to the second one. So I convert my Bitmap to string and pass it as an argument:


                            composable(
                                route = "${NavGraph.FilterScreen.route}/{screenShot}",
                                arguments = listOf(navArgument("screenShot") {
                                    this.type = NavType.StringType
                                })
                            ) {
                                FilterScreen(
                                    innerPadding = padding,
                                    navController = navController,
                                    screenShot = it.arguments?.getString("screenShot")
                                )
                            }

and I navigate from the first screen to the second one like this:

 navController.navigate(NavGraph.FilterScreen.route + "/${bitmapToString(it)}")

the problem is:

it seems because the string version of Bitmap is so long, the navigation can't handle it and gives the following error:

cannot be found in the navigation graph NavGraph(0x0) startDestination={Destination(0x78d845ec) route=home}

I'm saying that because everything worked when I replaced a small random string with a string containing Bitmap values.

I also tried to use parcellable. But I get the error that parcellable can not have a default value, so we must pass as a string. How can I solve this?

Upvotes: 7

Views: 1560

Answers (1)

Mahdi Iranmanesh
Mahdi Iranmanesh

Reputation: 580

You can save the image in a temporary file on the first screen and then read that image on the second screen and after that, you can delete that file. I make a sample project on Github, it's maybe not the best code for it but you get the idea

first screen:

 val context = LocalContext.current
 val path = context.getExternalFilesDir(null)!!.absolutePath

 val image = YOUR_BITMAP_IMAGE

 val tempFile = File(path , "tempFileName.jpg")
 val fOut = FileOutputStream(tempFile)
 image.compress(Bitmap.CompressFormat.JPEG , 100 , fOut)
 fOut.close()

 goToNextScreen()

second screen:

val context = LocalContext.current

val path = context.getExternalFilesDir(null)!!.absolutePath
val imagePath = "$path/tempFileName.jpg"

val image = BitmapFactory.decodeFile(imagePath)
File(imagePath).deleteOnExit() // Delete temp image

It may not be the best solution but it will do the job.

Upvotes: 0

Related Questions