Switching between Activities (screens...) in Android

This tutorial will show how to quickly create an Activity, and switch to another Activity using a ListView or a page full of buttons.

.Net folks can think of an Activity as a concept similar to a Form in a .Net Windows app. Each Activity you create is a new page in your app. An activity has essentially four states (blatantly stolen from the Android dev guide):

  • If an activity in the foreground of the screen (at the top of the stack), it is active or running.
  • If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
  • If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
  • If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

To start, you should be familiar with the Hello, World and List View  tutorials. Create a new Android project with 4 Class files:

  • HomeListView.java
  • Page1.java
  • Page2.java
  • Page3.java
     

Page1, Page2 and Page3 should each extend Activity, but HomeListView should extend ListActivity.

Under res/layout, create a new file called list_item.xml, and paste this xml into it:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

Create a string array to hold your ListView items by opening res/values/strings.xml and pasting the following inside the resources tag:

<string-array name="pages_array">
 <item>Page 1</item>
 <item>Page 2</item>
 <item>Page 3</item>
 <item>Switch to button mode</item>
</string-array>

Replace the onCreate method in HomeListView.java with the following code:

public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
  
 String[] pages = getResources().getStringArray(R.array.pages_array);
 setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, pages));
  
 ListView lv = getListView();
 lv.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
   Intent myIntent = null;
    
   if(((TextView) view).getText().equals("Page 1")){
    myIntent = new Intent(view.getContext(), Page1.class);
   }
    
   if(((TextView) view).getText().equals("Page 2")){
    myIntent = new Intent(view.getContext(), Page2.class);
   }

   if(((TextView) view).getText().equals("Page 3")){
    myIntent = new Intent(view.getContext(), Page3.class);
   }

   //if(((TextView) view).getText().equals("Switch to button mode")){
    //myIntent = new Intent(view.getContext(), ButtonPage.class);
   //}

   startActivity(myIntent);

  }
 });
}

Yes, the last if statement is commented out for now.

What we're doing here is creating an OnItemClickListener for the ListView and figuring out which item was clicked. The, we create an Intent to start a new Activity, and finally call startActivity to fire up the new activity (or new page, if you prefer).

You'll need to add all the activities to your main manifest file, so double click on AndroidManifest.xml, then click on the XML Source link to directly edit the xml. Paste the following xml in (you may already have HomeListView in there):

<activity android:name=".HomeListView" 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=".Page1"></activity>
<activity android:name=".Page2"></activity>
<activity android:name=".Page3"></activity>

The last step is to create something on each of the different Activity pages so you can see where you are. Paste the following code over the onCreate method in Page1.java, Page2.java and Page3.java (changing the "This is page 1" as appropriate...):

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     TextView tv = new TextView(this);
     tv.setText("This is page 1");
     setContentView(tv);
     }

Now, fire it up in the emulator. You should be able tselect page 1, 2 or 3 successfully.

What if you wanted to do the same thing using buttons instead of a ListView? To start, uncomment that fourth if statement in HomeListView.java, then create a new class called ButtonPage. In it's onCreate method, paste:

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.buttonpage);
    
     Button page1 = (Button) findViewById(R.id.Button01);
     page1.setOnClickListener(new View.OnClickListener() {
             public void onClick(View view) {
                 Intent myIntent = new Intent(view.getContext(), Page1.class);
                 startActivityForResult(myIntent, 0);
             }

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

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

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

     });

Next, you'll need to create the file res/layout/buttonpage.xml and paste in:

<?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">
    
 <Button android:text="Page 1"
        android:id="@+id/Button01"
        android:layout_width="250px"
        android:textSize="18px"
        android:layout_height="55px">
    </Button>
   
 <Button android:text="Page 2"
        android:id="@+id/Button02"
        android:layout_width="250px"
      android:textSize="18px"
        android:layout_height="55px">
    </Button>
   
    <Button android:text="Page 3"
        android:id="@+id/Button03"
        android:layout_width="250px"
      android:textSize="18px"
        android:layout_height="55px">
    </Button>
   
    <Button android:text="ListView Page"
        android:id="@+id/Button04"
        android:layout_width="250px"
      android:textSize="18px"
        android:layout_height="55px">
    </Button>
    
</LinearLayout>

Finally, open up AndroidManifest.xml once more and add:

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

Save everything and run. Now, when you click on the "Switch to button mode" item in the ListView, you'll jump to a screen with 4 buttons that should work similarly to your ListView.

Updated (2/23/2012): I've added the complete Eclipse project file for this tutorial to DropBox: ActivitySwitchingBlogDemo1.zip


Technorati Tags:

Print | posted @ Wednesday, November 17, 2010 3:07 PM

Comments on this entry:

Gravatar # re: Switching between Activities (screens...) in Android
by E. Howard at 12/1/2010 6:29 PM

Thanks for this great tutorial! I looked all over for something on this subject that actually made sense to someone new to Android and Java. Now that I have solved switching activities I can move on from this two day road block! Great job! Thanks!
Gravatar # re: Switching between Activities (screens...) in Android
by Cordell Hayes at 12/20/2010 8:04 PM

When i try to implement this code into a tab it does not work??? has anyone found the solution?
Gravatar # re: Switching between Activities (screens...) in Android
by Cordell Hayes at 12/20/2010 8:07 PM

PS i know how to do it with buttons..however i cant find the solution when using a list view..i got a feeling it has something to do with my XML....the app runs and all the tabs work except the tab with the activities
Gravatar # re: Switching between Activities (screens...) in Android
by Bill at 12/21/2010 9:27 AM

I added a post on how to switch Activities via tabs:
http://geekswithblogs.net/bosuch/archive/2010/12/21/android---switching-activities-with-a-tab-layout.aspx
Gravatar # re: Switching between Activities (screens...) in Android
by Cordell Hayes at 12/26/2010 9:01 AM

no i want to be able to use the tabs with this tutorial but crashed when it loads
Gravatar # re: Switching between Activities (screens...) in Android
by Gerry at 4/26/2011 5:30 PM

After having worked on Pocket PC working on Android is pure torture. I need to let the user select a file (one minute of work on Pocket PC) and maybe in another day or two I'll have it working on Android.
Gravatar # re: Switching between Activities (screens...) in Android
by Amol at 7/9/2011 4:33 AM

Hi,
Thanks for this code. it helps a lot
please import this all to work code properly

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

Gravatar # re: Switching between Activities (screens...) in Android
by Christopher at 9/10/2011 3:45 PM

Hallo
Tanks for the tutorial, I was looking for something similar but I have the following error " The element type "string-array" must be terminated by the matching end-tag "</string-array>"." when I am editing the "strings.xml". Here the complete string.xml,
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, HomeListView!</string>
<string name="app_name">HomeListView</string>
<string-array name="pages_array">
<string-array name="pages_array">
<item>Page 1</item>
<item>Page 2</item>
<item>Page 3</item>
<item>Switch to button mode</item>

</string-array>

</resources>

What do you think, thanks
Gravatar # @ Christopher
by Nick at 10/16/2011 9:10 PM

Chris, you open the <string-array> tag twice, so it wants you to end it twice.

...
<string name="app_name">HomeListView</string>
<string-array name="pages_array">
<string-array name="pages_array">
<item>Page 1</item>
...
Gravatar # re: Switching between Activities (screens...) in Android
by Yefta at 10/23/2011 8:25 PM

i have a problem with my project in switching activity. mt project contain 3 activity with 3 different layout, so one activity for one layout. but, the project can't be run and emulator says "The Application myProject has stopped unexpectedly"

this is my code:

public class myProject extends ListActivity {

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);

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

});

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

});

Button exitButton = (Button) findViewById(R.id.exit);
exitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
System.exit(0);
}

});
}
please help me to find what is wrong. thank you.
Gravatar # re: Switching between Activities (screens...) in Android
by Bill at 10/28/2011 8:48 AM

The code above looks ok, so I'm thinking it must be something in one of the other activities. Try running adb logcat to see the exact error that's killing it...
Gravatar # re: Switching between Activities (screens...) in Android
by bana at 10/29/2011 3:08 AM

\IntentProject\bin\IntentProject.apk installed on device

Done!

(That was the comment on ecplise console).

It has been installed on my emulator. But the app can't appear in my android emulator. Anybody know why?
Gravatar # re: Switching between Activities (screens...) in Android
by Jon at 11/9/2011 12:18 PM

Great article! I suggest making the code readable instead of the current black text. I've seen javascript libraries that can handle that functionality.
Gravatar # re: Switching between Activities (screens...) in Android
by najia at 12/12/2011 11:51 AM

While I run the project with buttonpage it gives error in emulatot,it says Application has stopped unfortunately.In logcat I see this
PID 555 Tag Androidruntime Text .. 30 more

Please can you tell me this is for what and how to get rid of this.
Gravatar # re: Switching between Activities (screens...) in Android
by Brad at 12/15/2011 12:34 PM

Thanks for the great post! I've worked with Android quite a bit but didn't know that you could switch between views within the same application using Intents, I always thought that you could only switch between applications with Intents. My team has been creating custom views and then just replacing the current view with the new one every time we need to change the screen, which gets really messy if there is a lot of screens. Thanks again, we'll definitely be using this in future development.
Gravatar # re: Switching between Activities (screens...) in Android
by PeteSchuette at 12/30/2011 8:21 PM

hey so im trying to make my own schedule app for fun and and i was trying to switch between my schedule view and assignment view so I used this code, however, when i click the button on the emulator, nothing happens... what am I doing wrong? from what I can tell I have everything you do?


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

public class ScheduleView
extends Activity
{

public void onCreate(Bundle savedInstanceState){
super.onCreate(null);
setContentView(R.layout.scheduleview);

Button scheduleToAssignments = (Button) findViewById(R.id.buttonScheduleView_Assignment);
scheduleToAssignments.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent toAssignment = new Intent(view.getContext(), MainSortClass.class);
startActivityForResult(toAssignment, 0);
}
});
}

}


also debug isn't picking anything up.
Gravatar # re: Switching between Activities (screens...) in Android
by Steve at 2/2/2012 1:35 PM

I get an error on this like:
String[] pages = getResources().getStringArray(R.array.pages_array);
the error states, "array can not be resolved or is not a field"
It says to add something to the R.Java file, but what do I put?
Gravatar # re: Switching between Activities (screens...) in Android
by Steve at 2/2/2012 1:38 PM

Sorry for wasting your time, I hadn't saved a page since altering it.
Gravatar # re: Switching between Activities (screens...) in Android
by Vasilis at 2/22/2012 1:19 PM

I followed the tutorial to the letter but when trying to "Switch to button mode" I get an "unexpected error". ButtonPage.java is

public class ButtonPage extends ListActivity{

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttonpage);

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

});

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

});

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

});

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

});


}}

Is something wrong?
Gravatar # re: Switching between Activities (screens...) in Android
by Harris at 12/14/2012 9:11 AM

This tutorial is great thanks man, it`s 1 step ahead for me in doing my task... many thanks man i hope you show us more tutorials about android for a beginner in android programming :)
Gravatar # re: Switching between Activities (screens...) in Android
by Harris at 12/14/2012 9:52 AM

By the way i keep trying to add new class yet it was keep getting force close
Gravatar # re: Switching between Activities (screens...) in Android
by Timothy at 1/21/2013 3:17 AM

am getting an error here
String[] pages= getResources().getStringArray(R.array.adobe_products);

Am told that array cannot be resolved or its not a field. What should i do to rectify this
Gravatar # re: Switching between Activities (screens...) in Android
by Bill at 1/23/2013 9:25 AM

Without seeing the entire project it's hard to say what the error could be - have you declared adobe_products inside a resource file?
Gravatar # re: Switching between Activities (screens...) in Android
by John Doherty at 7/26/2013 9:25 AM

How would you be able to show a alertdialog when a list view item is clicked? I would prefable want to know how to do it where the following code is pasted   myIntent = new Intent(view.getContext(), Page1.class); any help would be great!
Gravatar # re: Switching between Activities (screens...) in Android
by Fred Holm at 9/27/2013 1:19 PM

Thanks very much
Gravatar # re: Switching between Activities (screens...) in Android
by Fred Holm at 9/27/2013 1:19 PM

Thank you very much for this tut.
Gravatar # re: Switching between Activities (screens...) in Android
by jimmy at 4/21/2014 4:39 AM

this crashes on launch for me with this error:
Your content must have a ListView whose id attribute is 'android.R.id.list'
Gravatar # re: Switching between Activities (screens...) in Android
by jimmy at 4/21/2014 4:53 AM

Actually I've fixed that now (newbie alert here) how can I set the list view sub item text?
Gravatar # re: Switching between Activities (screens...) in Android
by dfsf at 8/22/2014 7:04 PM

lsdaf ojsasldkjf l;afsj ;ldsaf

Google</>
Gravatar # re: Switching between Activities (screens...) in Android
by sidi boy at 8/22/2014 7:06 PM

nice article :) here is my try have a look.

How to easily switch between Activities/Screen in Android
Post A Comment
Title:
Name:
Email:
Comment:
Verification: