Getting Started in Android Development
Part 28 -
The ability to transfer data between apps is fundamental to most apps. This is an easy process within Android. Android uses the concept of a bundle to do this.
A bundle can be thought of as a parcel or package that needs to be sent from one postal address to another. The package contains individual items. The package in Android terms is the bundle and the items are individual data that need to be sent from one activity to another.
In this example two activities were predefined. The user will enter the type of pet and the pet's age within the SenderActivity and the data will be "bundled up" and sent to the ReceiverActivity for display. A screenshot of the SenderActivity's layout is shown below followed by the XML layout code for the two activities.
XML code for the activity_sender.xml
XML code for the receiver_sender.xml
Within our SenderActvity we need to define our bundle and simply add the data to the bundle with the following code:
Bundle bundle = new Bundle();
The variable values are added to the bundle as a "key value pair". The key is a unique string identifier you enter. This value is used when retrieving the value in the receiving activity.
The next action is to start the ReceiverActivity. The key here is to add the bundle as extras.
Intent i = new Intent("com.nbstutorials.tutorialset2.RECEIVER");
That really is all there is to creating the bundle and sending it to the receiving activity. The full code for the SenderActivity.java file is shown below.
On the receiving side we need to also define an object of the bundle class.
Bundle bundle = getIntent().getExtras();
The method getIntent() returns the intent that started the ReceiverActivity activity. In this example that is the SenderActivity. We then also need to get the extras or the bundle from that in intent with the method getExtras(). It is then simply a case of extracting the data from the bundle and assigning the value to a variable.
String pet = bundle.getString("pet_type");
int age = bundle.getInt("pet_age");
Again, that is really all there is to the receiving side. The two screenshots below show the sending and receiving layouts.
After this tutorial your ReceiverActivity.java file should look similar to the one below.
This was the first part of Tutorial set 2 and so your MainActvity.java file should look similar to the one below:
Your activity_main.xml file should look similar to the one below:
Your AndroidManifest file should look similar to the one below:
And there should also be a colors value file similar to the one below:
Download Download tutorial set 2