Pass data between Activities | Multi-page apps | Android Devs

Jul 4, 2021·

2 min read

Pass data between Activities | Multi-page apps | Android Devs

Hey Android Devs, in this article, I will show how you can pass data between screens (both Activities and Fragments).

Please check these articles before reading this:
Navigation in multi-page apps |Part 1
Navigation in multi-page apps |Part 2

Let's be clear, what kind of data we want to share. Images or Videos or Documents ?? No, you won’t share these kinds of media across screens often. Sometimes you just need the image path or document URL. Right.

So in most cases, you will share primitive (int, float, double) or String or primitive array types.
If you are coming from other top-level programming languages or even Java /Kotlin, you may heard about Dictionaries ( Object in Javascript, HashMap in Java and Kotlin, Dictionaries in Python, Associative Arrays in PHP).

Yes, you are right, Key-Value pairs. We will use this data structure to share information. For example, you have to pass name and email,

{
    "name": "YourName",
    "email": "name@company.org",
}

This is the simplest form of Key-Value pair.

How can we create this structure in Android, using any data structures?
No, you won’t, there is a class already built for these kinds of purposes.

It’s called Bundle | Android Docs.

In Activities, you create an Intent to launch new Activity.

val intent = Intent(this, TargetActivity::class.java)
startActivity(intent)

1.First create a Bundle instance.

val bundle = Bundle()

This is equivalent to

{
}

2.Add data to bundle

bundle.putString("name", "YourName")
bundle.putString("email", "name@company.org")

This is equivalent to

{
    "name": "YourName",
    "email": "name@company.org",
}

3.Insert bundle into the intent

intent.putExtra(bundle)

Now, the bundle object is being passed to the target activity.

There are other ways to pass bundles in intents.

See => 3 ways to pass Bundles through Intents | StackOverflow

Now, how you can retrieve the data in TargetActivity. It’s simple
You can do that with the incoming intent object.
It can be accessed by

class TargetActivity : AppCompatActivity {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_target)
        val name: String? = intent.getStringExtra("name")
        val email: String? = intent.getStringExtra("email")
    }
}

It’s so simple right. : )

Note: To share custom objects, you have two options.
1. Parcelable
2. JSON

Thank you : )
Follow me on Twitter
Happy Coding…