Passing data between Activities in Android is pretty simple than you think with the use of Intent.
Intent
As the name implies, Intent is “an intention to do something”. An intent can be used in several use cases.
- To start an activity
- To start a service
- To deliver a broadcast
We will look into the first use case in this post. In order to start an Activity, you could use the following code.
Intent intent = new Intent(PackageContext, NextActivity.class);
startActivity(intent);
This will create a new intent and the NextActivity will be started after executing the code.
Passing data between activities
While creating the intent and starting it, we can pass information to the next activity to be started. Let’s see how we could pass data.
Intent intent = new Intent(PackageContext, NextActivity.class);
intent.putExtra("keyName","value");
startActivity(intent);
This will create a new intent and the NextActivity will be started after executing the code.
The following sample code will pass the value username with the key “loggedUser”. So that the new Activity can retrieve the value by accessing it though the key.
intent.putExtra("loggedUser","username");
Accessing the data from the new Activity
Intent intent = getIntent(); String loggedUser = intent.getStringExtra("loggedUser");
The above code will give you the loggedUser information which was passed from the previous activity.