Skip to content

Half Dozen Hello Worlds Part 6 – Opening Activities

Intents

You can think of an intent as a way for the developer to tell Android what he intends to happen while his application is running. That is, you specify what action you want to occur at run time. We are going to use an intent to tell Android to show the user a different activity on their screen. But first, we need to add some code to figure out which activity the user wants to see. We do this by overriding the method onListItemClick from ListActivity.

@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	if (position == 0) {
    		//Hello 1
    	} 
    	if (position == 1) {
    		//Hello 2
    	}
    }

Now, let’s add our intents to this code. I added the class Hello1 by expanding the src folder, right clicking on my package (com.learnandroid.helloworld) and selecting New -> Class from the context menu. I name the class Hello1 and copy the source code from Part 1 of our Hello World series. Then I update the onListItemClick method to call this class.

protected void onListItemClick(ListView l, View v, int position, long id) {
    	if (position == 0) {
    		startActivity(new Intent(this, Hello1.class)); 
 
    	} 
    	if (position == 1) {
    		//Hello 2
    	}
    }

startActivity tells Android to launch a new activity and display it to the user. It expects an Intent as it’s argument. In this case we used a very simple Intent, telling Android to we intend to use Hello1.class as our Activity, in the current context (this). In future articles we will look into some of the other sorts of Intent available to us, but for now this simple identifying of a specific Activity will suit our needs.

If you run this in your emulator right now you will see a list with two items, “Hello 1” and “Hello 2”. Clicking on Hello 2 will do nothing, as expected. Clicking on Hello 1… will cause your application to crash!

Crash

What gives?
Your Hello1.class file is fine, and we know it works since we got the source code from a previous example. What happened is that Android tried to start an Activity named Hello1.class among all of the activities it knew about and crashed when it wasn’t found. So how do we tell Android about our Hello1 activity? We need to add it to the AndroidManifest.xml.

Next: Using Your Activity

{ 2 } Comments