Lecture 3 - Calling Sub-Activities

home | previous | next

Overview

Most applications have multiple screen views. Android applications show screen views through activities. We will learn using activities, calling other activities with data and retrieving data returned from sub-activity.

Calling Sub-activities

Example 3.1

Intent intent = new Intent(this, Act2.class);
intent.putExtra("name", "Apple");
intent.putExtra("quantity", 5);
startActivity (intent);

Example 3.2

Intent intent = getIntent();
String name = intent.getStringExtra("name");
int quantity = intent.getIntExtra("quantity", 0);
if (name != null)
{
   String text = name + " : " + Integer.toString(quantity);
   textView2.setText(text);
}

Exercise 3.1

Make a new application with 3 activities.
Place widgets like follows:

Activity A (Launcher Activity):
TextView (textView1)
Button (button1)

Activity B:
TextView (textView1)
TextView (textView2)
Button (button1)

Activity C:
TextView (textView1)
TextView (textView2)

To do 1:
Display activity names on textView1 of each activities.

To do 2:
When the user clicks button1 of activity A, start activity B passing 1 string data and 1 integer data.

To do 3:
When activity B starts, retrieve the data and display them on textView2.

To do 4:
When the user clicks button1 of activity B, start activity C passing 1 string data and 1 integer data.

To do 5:
When activity C starts, retrieve the data and display them on textView2.

Results Returned from Sub-activities

Example 3.3

Intent intent = new Intent(this, A.class);
startActivityForResult(intent, ACT_A);

Example 3.4

Intent intent = new Intent();
intent.putExtra("name", "Apple");
setResult(RESULT_OK, intent);

finish();

Example 3.5

protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
   if (resultCode != RESULT_OK)
   {
      textView1.setText("");
      return;
   }

   if (requestCode != ACT_A
       && requestCode != ACT_B
       && requestCode != ACT_C)
   return;

   textView1.setText(data.getStringExtra("name"));
}

Exercise 3.2

Make a new application with 4 activities. Place widgets like follows:

Activity Home (Launcher Activity):
Button (button1)
Button (button2)
Button (button2)
TextView (textView1)

Activity A:
TextView (textView1)

Activity B:
TextView (textView1)

Activity C:
TextView (textView1)

To do 1:
Display activity name A on button1, B on button2, C on button3.

To do 2:
Display activity names on textView1 of activity A, B, C.

To do 3:
When the user clicks a button of activity Home, start the activity of the name, which is written on the button, asking result.

To do 4:
When the user clicks the back button on activity A, B or C, set the result with some data.

To do 5:
When the user sees activity Home again, show the data returned from the sub-activity on textView1.

Related subjects

Resources

Links