How To Work With Multiple Activities In Android



Hi,Today I am going to show you how to work with multiple Activity and How to exchange data between those Activity.When we developing application we have to deal with several activity in android.So there should be good messaging facility to work around them.In Android,Intents is the thing that we use for that.
Intent object is type of “android.content.Intent” use for sending and receiving data between android activity and services.It use for send asynchronous massages between android applications.
Intent can contains
  1. Data,We can send data to another activity using intent data.We can put data in to Intent as Key\Value pair.
  2. Intent Filter,When we using Implicit Intent,we can filter that using intent filter if several application exist for fulfill our Intent request.For example,Think If your application wants send email and your mobile have several applications for sending email.then we can set which email client to use in our application using Intent filter.
Today I create simple example to demonstrate how to work with multiple activity in android application.here I have two Activity which MainActivity and ColorSelectorActivity.following figure shows you two Activity.
layout
First one call second activity when Select Color Button press for selecting color and second activity return selected color when OK Button press.
Let see how I implemented Example.
  1. first create project and change main.xml
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="10dp"
            android:text="Color Selector"
            android:textAppearance="?android:attr/textAppearanceLarge" />
        <FrameLayout
            android:id="@+id/colorBox"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:layout_gravity="center"
            android:background="#ffffff" >
        </FrameLayout>
        <Button
            android:id="@+id/selectColor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="10dp"
            android:text="Select Color" />
    </LinearLayout>
  2. Then create new layout call colorselector.xml and add folowing code to it.
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        <RadioGroup
            android:id="@+id/radioGroupColors"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" >
            <RadioButton
                android:id="@+id/radioRed"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="Red"
                android:textColor="#ff0000" />
            <RadioButton
                android:id="@+id/radioBlue"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Blue"
                android:textColor="#0000ff" />
            <RadioButton
                android:id="@+id/radioGreen"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Green"
                android:textColor="#00ff00" />
            <RadioButton
                android:id="@+id/radioBrown"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Brown"
                android:textColor="#a52a2a" />
            <RadioButton
                android:id="@+id/radioYellow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Yellow"
                android:textColor="#ffff00" />
        </RadioGroup>
        <Button
            android:id="@+id/buttonOk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:minWidth="100dp"
            android:text="OK" />
    </LinearLayout>
  3. Then Make following changes to MainActivity.java
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    public class MainActivity extends Activity {
        private static final  int COLOR_SELECTOR=0;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            //get the Select Color button
            Button selectColorButton = (Button) findViewById(R.id.selectColor);
            //set action listener for button
            selectColorButton.setOnClickListener(new OnClickListener() {  
       @Override
       public void onClick(View v) {
        //first create new intent to call ColorSelectorActivity
        Intent request =new Intent(MainActivity.this, ColorSelectorActivity.class);
        /*then start new ColorSelectorActivity and waiting for its result
        here we use COLOR_SELECTOR unic code because we might have lot of
        activity call from this activity for ignoring complict of that
        we use unic request code for each activity*/   
        startActivityForResult(request, COLOR_SELECTOR);   
       }
      });
        }
        //this is the method that call when Activity result comes
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         //check which activity gives data
         switch(requestCode){
         //checking for our ColorSelectorActivity using request code
         case COLOR_SELECTOR:
          //check whether result comes with RESULT_OK (That mean no problem in result)
          if(resultCode == RESULT_OK){
           //then get the color string that return from our ColorSelectorActivity
           String color= data.getExtras().getString("selectedColor");
           //then set background color
           findViewById(R.id.colorBox).setBackgroundColor(Color.parseColor(color));
          }
         }
        }
    }
  4. Finally Add new Activity called ColorSelectorActivity.java and make following changes to it
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.RadioGroup;
    import android.widget.RadioGroup.OnCheckedChangeListener;
    public class ColorSelectorActivity extends Activity {
     //variable for holding select color;
     private String color = "#ff0000";
     //intent for use when returning to main activity
     Intent selectedColor;
     
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.colorselector);
      //get our Radio Button Group
      RadioGroup colors = (RadioGroup) findViewById(R.id.radioGroupColors);
      //get our OK Button
      Button ok = (Button) findViewById(R.id.buttonOk);
      //create new selectedColor Intent
      selectedColor = new Intent();
      //set action listener for RadioButton Checked Changed
      colors.setOnCheckedChangeListener(new OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(RadioGroup group, int checkedId) {
        //set color according to selected RadioButton
        switch (checkedId) {
        case R.id.radioRed:
         color = "#ff0000";
         break;
        case R.id.radioBlue:
         color = "#0000ff";
         break;
        case R.id.radioGreen:
         color = "#00ff00";
         break;
        case R.id.radioBrown:
         color = "#a52a2a";
         break;
        case R.id.radioYellow:
         color = "#ffff00";
         break;
        }
       }
      });
      //set action listener for Ok Button
      ok.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
        /*set Our selected color value in selectedColor intent with selectedColor key,
         this is using for getting color from result in main activity*/
        selectedColor.putExtra("selectedColor", color);
        //set result with our selectedColor intent and RESULT_OK request code
        setResult(RESULT_OK, selectedColor);
        //then finish the activity
        finish();
       }
      });
     }
    }
  5. Comment line shows you important thing and following screen shots show you working application.

start colorselectionselectedcolor

YOU CAN DOWNLOAD SOURCE CODE HERE AND GIVE YOUR FEEDBACKS

Labels: , ,