Passing Data to Sub Activities

Passing data to (Sub)Activities is, once again, not hard to manage. One can use so called Bundles, which are more or less ordinary HashMap's that can take only trivial data types, to carry information from one Activity to another. Just remember where we started our SubActivity in the last chapter:

/* Create an Intent to start

* MySecondActivity. */ Intent i = new Intent(

StartingSubactivities.this, MySecondActivity.class); /* Send intent to the OS to make

* it aware that we want to start

* MySecondActivity as a SubActivity. */ startSubActivity(i, 0x1337);

Right between these two lines, we will put the following:

/* Create a bundle which will be

* attached to the Intent, to carry

* information to our SubActivity. */ Bundle b = new Bundle();

b.putString(MY_DEFAULTSTRING_ID, ""); /* Attach Bundle to our Intent. */ i.putExtras(b);

Where MY_DEFAULTSTRING_ID can be any identifying String you can imagine. There is also a method Intent.putExtra(...,...) which takes only one information each call, which we could have used also.

Now we have to extract that information within our SubActivity. Every Activity can access the original Intent it was started with, by calling getIntent(). If there was a Bundle attached to the Intent we can grab that by using getlntent () .getExtras (). In this case we, we will fill the EditText, where the user would type the keyword(s) with the DefaultString we passed over the Intent :


/* Get the Bundle from the Intent

* this Activity was started with.*/ Bundle bundle = getIntent().getExtras(); /* Extract the default keyword

* by using the public ID we

String default_keyword = bundle.getString(

StartingSubactivities. MY_DEFAULTSTRING_ID);

this.et_keyword = (EditText)this.findViewById(;

/* Set the default keyword to the EditText. */ this.et_keyword.setText(default_keyword);

So let's resume what you have learned up to here:

• Create an simple Application using a XML Layout

• Do the same with a Java-based Layout

• Run Android Applications

• Using the LogCat for debugging purpose

• Use Intents to start (Sub)Activities

• Find Views defined in XML to use them in Java Code

• Handle Clicks to Views

• Return values from SubActivities

• Pass data to SubActivities using Bundles

Not bad for now

Was this article helpful?

+1 0


  • petros
    How will you pass data to subactivities?
    2 years ago
  • elias
    11 months ago

Post a comment