How can you pass data between activities in Android?
How can you pass data between activities in Android?
32127-Jun-2023
Updated on 28-Jun-2023
Home / DeveloperSection / Forums / How can you pass data between activities in Android?
How can you pass data between activities in Android?
Aryan Kumar
28-Jun-2023There are two ways to pass data between activities in Android:
putExtra()
method to add the data to the intent. The data can be of any type, such as strings, integers, or objects. When the activity is started, the data will be passed to the activity'sonCreate()
method.Here is an example of how to pass data using intents:
Code snippet
In this example, we are creating an intent to start the
SecondActivity
class. We are also adding a string with the key "name" and the value "John Doe" to the intent. When theSecondActivity
is started, the data will be passed to the activity'sonCreate()
method.Here is an example of how to pass data using shared preferences:
Code snippet
In this example, we are getting the data from the shared preferences file. The file is named "my_preferences" and it is stored in the private mode. The key of the data is "name" and the default value is an empty string.
Which method you use to pass data between activities will depend on your specific needs. If you need to pass a small amount of data, then using intents is a good option. If you need to pass a larger amount of data or if you need to persist the data across app sessions, then using shared preferences is a good option.