Search code examples
androidkotlinandroid-jetpack-compose

Cannot get context in Compose


I am trying to add a popover to my jet compose app. The Popover.kt is in the same folder structure.

But, I keep getting a context error whilst trying to add the shareText and copyText to my onShareClick and onCopyLinkClick in the MainActivity.kt. I get context errors, even when I try to import the suggested codes.

Unresolved reference: context
Cannot access 'CompletedContinuation': it is internal in 'kotlin.coroutines.jvm.internal'
Cannot access 'NoOpContinuation': it is private in file
Type mismatch: inferred type is CoroutineContext but Context was expected

This is the code I am trying to attach to the MainActivity.kt.

// POPUP OVERLAY
if (showPopover) {
    Popover(
        onDismiss = { showPopover = false },
        onShareClick = {
            shareText(context, "Invite people to join you in the app!")
        },
        onCopyLinkClick = {
            copyText(context, "Invite people to join you in the app!")
        }
    )
}

fun shareText(context: Context, text: String) {
    val intent = Intent(Intent.ACTION_SEND).apply {
        type = "text/plain"
        putExtra(Intent.EXTRA_TEXT, text)
    }
    context.startActivity(Intent.createChooser(intent, "Share text via"))
}

fun copyText(context: Context, text: String) {
    val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
    val clip = android.content.ClipData.newPlainText("Invite Text", text)
    clipboard.setPrimaryClip(clip)
    Toast.makeText(context, "Copied!", Toast.LENGTH_SHORT).show()
}

Solution

  • That's most likely caused by a bad import, something like this:

    import kotlin.coroutines.jvm.internal.CompletedContinuation.context
    import kotlinx.coroutines.flow.internal.NoOpContinuation.context
    

    The context cannot be imported, it must be retrieved during runtime. Remove the import and add this above your Popover instead:

    val context = LocalContext.current