You are currently viewing How to pass data between MainActivity and a Fragment?

How to pass data between MainActivity and a Fragment?


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 (, 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("" + 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("$barcode/$calories/$percent").readText() ........

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