B
B
Berry902020-12-20 08:43:03
Android
Berry90, 2020-12-20 08:43:03

How to set image from MainActivity to Image Jetpack Compose?

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        GlobalScope.launch(Dispatchers.IO) {
            val url = URL("https://picsum.photos/300/300")
            val connection = url.openConnection() as HttpURLConnection
            connection.doInput = true
            connection.connect()
            val inputStream = connection.inputStream
            val bitmap = BitmapFactory.decodeStream(inputStream)

            launch(Dispatchers.Main) {
                setContent {
                    PlayGroundTheme {
                        Surface(color = MaterialTheme.colors.background) {
                            Greeting("Android", bitmap)
                        }
                    }
                }
            }
        }
        
    }
}

@Composable
fun Greeting(name: String, bitmap: Bitmap) {
    Column(Modifier.fillMaxWidth().padding(16.dp)) {

        Image(bitmap.asImageBitmap(), Modifier
                .preferredHeight(300.dp)
                .fillMaxWidth() )

        Text(text = "Hello $name")
    }

}


it works like that, but I would like to hang the download separately on the image, it turns out through xml, when applying coroutines through compose it writes:
@Composable invocations can only happen from the context of a @Composable function,
how to access the image separately in MainActivity?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
illuzor, 2020-12-20
@Berry90

1) No need to use GlobalScrope on android at all. As a last resort, there is a lifecycleScope;
2) The error says in plain text that a composable function can only be called within a composable function;
3) To upload images, you should use the Accompanist library

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question