Android: How to switch between Activities

Posted May 24th @ 10:38 pm by Boyan

In my great expectations of Google Android coming to Canada on June 2nd, I’ve started experimenting with developing some apps for the Android platform. My first app is called “The Taxman” and will calculate the amount of tax you owe per year in your province/state – well only Canada for now.

I had trouble adjusting to what an “Activity” was and how to handle it. Here is a quick and dirty way to create an Activity, and to switch to another Activity (think of it as another screen) on the click of a button.

1. Create a new Android project – or you might already have one created.

01 new project

2. Add a new Class that extends android.app.Activity. You need a total of two classes that extend Activity. You will switch from one Activity to another.

02 new class

03 new class 2

3. Now, we’ll create two XML files to store the layout of each Activity. Under the res/layouts directory create a copy of main.xml

04 xml files

4. Each XML file will contain 1 button. On the click of the button, the Activities will switch.

main.xml will contain:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"  >

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#000000"
    android:text="This is Activity 1" />

       <Button android:text="Next"
        android:id="@+id/Button01"
        android:layout_width="250px"
            android:textSize="18px"
        android:layout_height="55px">
    </Button>    

</LinearLayout>

main2.xml will contain:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"  >

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#000000"
    android:text="This is Activity 2" />

       <Button android:text="Previous"
        android:id="@+id/Button02"
        android:layout_width="250px"
            android:textSize="18px"
        android:layout_height="55px">
    </Button>    

</LinearLayout>

So each Activity will have a text that says “This is Activity x” and a button to switch the Activity.

5. Add the second Activity to the main manifest file. Open AndroidManifest.xml and add:

        <activity android:name=".Activity2"></activity>

The final result will look similar to this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.warriorpoint.taxman2"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Activity1"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Activity2"></activity>
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest>

If you forget to do this, then the you will get a Null Pointer exception because “Activity2” will not be found at runtime. It took me some time to find out how to find what Exception was getting thrown as well. I will include how to debug and look at Exceptions in another future post.

5. Open Activity1.java and enter the following code:

package com.warriorpoint.taxman2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Activity1 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button next = (Button) findViewById(R.id.Button01);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), Activity2.class);
                startActivityForResult(myIntent, 0);
            }

        });
    }
}

Here’s a quick explanation of what this does:

- setContentView(R.layout.main) makes sure that main.xml is used as the layout for this Activity.

- Gets a reference to the button with ID Button01 on the layout using (Button) findViewById(R.id.Button01).

- Create san OnClick listener for the button – a quick and dirty way.

- And the most important part, creates an “Intent” to start another Activity. The intent needs two parameters: a context and the name of the Activity that we want to start (Activity2.class)

- Finally, the Activity is started with a code of “0”. The “0” is your own code for whatever you want it to mean. Activity2 will get a chance to read this code and use it. startActivityForResult means that Activity1 can expect info back from Activity2. The result from Activity2 will be gathered in a separate method which I will not include here.

6. Open Activity2.java and enter the code below:

package com.warriorpoint.taxman2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Activity2 extends Activity {

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

        Button next = (Button) findViewById(R.id.Button02);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }

        });
    }

This code does the following:

- Sets main2 as the layout for this Activity

- Gets a reference to Button02 and creates an OnClick listener

- In the OnClick listener, the Activity finishes with finish(). setResult() returns information back to Activity 1. In this example, it returns no information; and Activity1 doesn’t even have the listener to receive this information anyway.

That’s it! Run it!

05 run

The app will load in Activity 1:

06 activity 1

When you click the button you will see Activity 2. There are no animations, no tweens, etc, so the screen will just “change”. I’ll talk about animations in future posts.

07 activity 2

And clicking on the button “Previous” here will go back to Activity1.

Still to come:

1. How to create animations when switching screens.

2. How to switch using a dragging motion of your finger.

3. How to see a log of the exceptions that your app throws.

Advertisement


-->

25 Comments

  1. Tim Almond
    June 11, 2009 at 07:52

    A simple question…

    What makes the emulator start with Activity1 rather than Activity2? Is it the addition of

    ?

    Thanks.
    Tim

  2. Boyan
    June 16, 2009 at 11:22

    Hey Tim,

    If I’m not mistaken it’s the following lines in the Manifest that make Activity1 the default activity:




  3. Boyan
    June 16, 2009 at 11:22

    The opening and closing tags got cut out.
    intent-filter
    action android:name=”android.intent.action.MAIN” /
    category android:name=”android.intent.category.LAUNCHER” /
    /intent-filter

  4. ceveni
    July 6, 2009 at 06:36

    If your screens are simple it is better to use Layouts instead of definining it as activity by switching Layouts

  5. Boyan
    July 6, 2009 at 22:08

    Cool. Thanks

  6. needhelp
    August 12, 2009 at 00:54

    how can i find out need tip solve those problem?

    1. How to create animations when switching screens.

    2. How to switch using a dragging motion of your finger.

    3. How to see a log of the exceptions that your app throws.

    thanks

  7. Chris
    August 22, 2009 at 01:19

    I thought this was a great tutorial–straightforward, lots of detail, and it picked up right where the sample “Hello, Android” app left off.

    I couldn’t understand why my version of your application crashed whenever I pressed the Next button. Finally I figured it out–thanks to your subsequent post about reading the logs:

    E/AndroidRuntime( 1001): android.content.ActivityNotFoundException: Unable to find explicit activity class {tld.domain.helloandroid/tld.domain.helloandroid.Activity2}; have you declared this activity in your AndroidManifest.xml?

    Pretty clear message! Since I had been building off the “Hello, Android” sample, I just added a new class file for Activity2, which wasn’t properly registered in the AndroidManifest.xml file. Just thought I’d mention that here in case anyone else makes the same mistake.

  8. Boyan
    August 23, 2009 at 12:17

    Awesome, thank you very much Chris for posting that; and thanks for the kind words as well.

  9. neil
    September 29, 2009 at 01:55

    Hi!
    do you have an idea on passing an object Bundle back to the first activity and how can you retrieve the data?

    Nice Tutorial. Thanks for the info…

  10. John
    October 16, 2009 at 08:41

    And if I want to switch activity trought MenuItem, how can i do?
    Thanks

  11. Safa
    November 26, 2009 at 13:28

    Hi there. I’d like to learn to program on Android but I’m completely clueless about how the activities work. I wanted to ask, how do you pass parameters to activities? I want to be able to change colour settings for a “game” activity based on a selection made in a “Settings” activity. Could you tell me how to pass variable values across activities?

    Thanks

  12. madhumitha
    December 3, 2009 at 18:45

    hey..
    that really helped. thanks:)

  13. MD Rafiqul Islam
    December 7, 2009 at 07:17

    this is really great!!!

    thanks a lot.

  14. manic miner
    December 11, 2009 at 11:47

    Many thanks for this! So many of the demos out there just demo API fnality, all just in Java, all in onCreate, with zero clues as to how to manage this kind of simple application flow. What are we supposed to do, fill onCreate with dozens of lines of Java?! :P Thanks again ;)

  15. Jay Pena
    December 15, 2009 at 21:53

    Just what I’m looking for!

  16. MNutsch
    December 27, 2009 at 17:18

    Thanks for writing.

  17. MNutsch
    December 27, 2009 at 17:18

    …this.

  18. Werner
    December 28, 2009 at 18:39

    Hi, thanks for this. Best tutorial i found.

  19. kendog
    January 5, 2010 at 11:52

    i have to agree with everyone. this is an excellent tutorial. thank you so much for putting it together.

  20. Justin
    January 7, 2010 at 11:34

    Thanks! I’ve been looking at how to do this for a couple of hours!

  21. sanooj
    January 15, 2010 at 04:20

    me also stuck up for two days……..

    thank you very much its working fine…..

  22. par
    February 3, 2010 at 23:28

    Great post, took about 10 minutes to get the example working! Thanks a bunch!

  23. Paul Gillingwater
    February 5, 2010 at 19:48

    An excellent introduction for one who is learning to develop with Android. Thanks for taking the time to write it up!

  24. sam
    February 9, 2010 at 08:55

    Hi,
    In am developing a android application. The framework is such that I dont allow Activities to laucnh each other.

    Eg: ActivityA can only talk to datahandlerA
    ActivityB can only talk to datahandlerB
    datahandlers can talk to any other datahandlers.

    Some operation happens on ActA. It informs DHA. DHA does some network operation. It informs DHB. DHB does some process than launches ActB.

    Please let me know how this can be done.

    Thanks
    Sam

  25. uday
    March 8, 2010 at 00:59

    thanks……..got it

Leave a comment

Standard Login

Options:

Colors