Navigation in Jetpack Compose

Sep 10 2024 · Kotlin 1.9, Android 14, Android Studio Jellyfish

Lesson 03: Pass Data

Demo

Episode complete

Play next episode

Next
Transcript

In this demo, you’ll continue to build on the movie-booking application from the previous lesson.

Open the starter project and find a file named BookingConfirmationScreen.kt that contains the composable to show the booking-confirmation details to the user. Notice that it has a button with the text “SHARE”.

In this part of the lesson, you’ll define the logic to share the movie booking confirmation details externally to other app(s) using an intent, when that button is clicked.

Note that the navigation logic from the ticket-selection screen to the booking-confirmation screen has been set up for convenience. Also, note that a placeholder function named shareBookingDetails() has been defined, wherein you’ll define the logic to pass data externally. This will be called when the user clicks the ‘SHARE’ button.

Start by defining the intent in the shareBookingDetails() function body:

val intent = Intent(Intent.ACTION_SEND)

Now, set up the type of data and the data’s value using the putExtra(...) function:

val intent = Intent(Intent.ACTION_SEND).apply {
  type = "text/plain"
  putExtra(Intent.EXTRA_SUBJECT, "$movieName booking details")
  putExtra(Intent.EXTRA_TEXT, "You have booked $ticketCount ticket(s) for $movieName")
}

In the code above, the key Intent.EXTRA_SUBJECT specifies the subject of the data being shared. Email apps, for example, support subject header for messages being shared. For apps that don’t support a subject line, this message will be skipped. Intent.EXTRA_TEXT specifies the body of the message being shared. This is the most common form of text shared between apps.

Note that because multiple operations had to be performed on the intent variable, using the scope function apply makes the code more concise.

The next step is to create a chooser using the Intent.createChooser() function so the user can choose which app to share data with. The last step is to launch the returned intent instance using the startActivity() function.

context.startActivity(
  Intent.createChooser(intent, "Share movie booking details")
)

Finally, call the function shareBookingDetails() when the user clicks the button:

Button(
  modifier = modifier.fillMaxWidth(),
  onClick = {
    shareBookingDetails(
      context = context,
      movieName = movieName,
      ticketCount = ticketCount,
    )
  }
) {
  ...
}

Note that the text ‘Share movie booking details’ isn’t displayed on the bottomsheet. Intent.createChooser displays the title string only when the action type isn’t ACTION_SEND or ACTION_SEND_MULTIPLE. In this case, you pass a string to ensure that the code compiles fine.

Great — you’ve successfully shared data outside your app!

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion