How to pass data between MainActivity and a Fragment?

How to pass data between MainActivity and a Fragment?

Hi.

I’ve created a barcode scanner that once scanned writes the barcode to a string variable.

I now want access to that variable back on the MainActivity.

I can’t see how to do it at all.

I’ve followed an example online (https://johncodeos.com/how-to-pass-data-between-fragments-in-android-using-kotlin/), but as I’m finding quite often with these tutorials is that they are out of date, or simply don’t work. This one for instance, highlights things like “content_id” in red and won’t compile.

So, before I go down yet another rabbit hole…is there a simple way of passing say String data back to the MainActivity from a Fragment?

I have this:


val thread = Thread(Runnable { try { var json = URL("https://world.openfoodfacts.org/api/v0/product/" + result.contents.toString() + ".json").readText() val mapper = jacksonObjectMapper() mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) var products: Json4Kotlin_Base = mapper.readValue(json) var product_name = products.product!!.product_name var calories = products.product!!.nutriments?.energy_value var barcode = result.contents.toString() Thread(Runnable { this@MainActivity.runOnUiThread(java.lang.Runnable { this.text_food.text = product_name this.text_calories.text = calories.toString() + " calories per 100g" this.button_add_food.visibility = View.VISIBLE this.text_barcode.text = barcode // need to put variables here: barcode/calories/percent }) }).start() } catch (e: Exception) { e.printStackTrace() } }) thread.start()

…in MainActivity.kt

A bit later – after some user input on HomeFragment, the user clicks a button and, I have:


 button_add_food.setOnClickListener { val thread = Thread(Runnable { try { // and access them here: var json = URL("http://www.myurl.co.uk:5001/api/food/1/$barcode/$calories/$percent").readText() ........

submitted by /u/dchurch2444
[link] [comments]