Monday, December 19, 2011

Android Tutorial Part3 - Using Intent to start an activity.

Hello,

I think it's time to add more than one page to our app. You may have read that each screen/page in android is called an activity. To start an activity we use the intents.

To implement an activity we need two files
  1. a class file which extends the Activity
  2. a xml file which describes how the activity looks like. If you want you can avoid the xml!. But you have to describe how the class looks like in the class file.
You should mention the name of the activity in the AndroidManifest.xml file in order to make it accessible by the system. We will come into this after declaring the activity.

To introduce the use of intents I will be creating a new project with a button on the home screen. When you taps it, you will be taken to the next activity.

Lets start together. Create a new android project with whatever name and target you like. After that place a button on the first activity. In my last post I had said how to implement the button action. I think you had done upto that in this project also!

For those who forget those steps check my steps below.

1. Created a project with following details
  • Project Name: Sample2
  • Build Target: Android 2.2
  • Package Name: com.android.sample2
You can change the above settings as you wish

2. Added a button(Next Activity) on the main.xml file with onClick action goToNextActivity. This action has to be defined in the class file. The main.xml now looks as

<?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:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="goToMyNextActivity"
        android:text="Next Activity" />

</LinearLayout>

Before start editing the class file I'm going to create the second activity. For that right click your package name inside the src folder in 'Package Explorer'. In my case the com.android.sample2.

Select New>Class. In the window that appears give the name of the second activity and click 'Finish'. You can name the activity as you wish. I named it as SecondActivity.

Now in the package explorer just below the Sample2Activity ypu can see the new activity we created. It's time to create an xml file for this activity.

For creating the xml file right click the layout folder inside the res folder. Select New>Android XML Layout File. If you didn't see the 'Android XML Layout File' then select the 'other' option and find it from the 'Select a wizard' window. Once selected click 'Next'.

Enter the name of your xml file in 'File:'. Here also you can enter the name you like! But names must contain only lowercase a-z, 0-9, or _.

I entered second_activity and clicked 'Finish'. The default root element selected will be LinearLayout. We will discuss on different layouts later. For now use the LinearLayout.

On the new xml file add a text view and display whatever you like. I added the following code in second_activity.xml

 <?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" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="THIS IS MY SECOND ACTIVITY" />

</LinearLayout>

Now we have to connect this layout to the class file. For that open the SecondActivity.java. It will be like

package com.android.sample2;

public class SecondActivity {

}

As I said earlier the class file should extend the Activity.

package com.android.sample2;

import android.app.Activity;

public class SecondActivity extends Activity{

}

The import will automatically come when you types the class name. If not simply press Ctrl+Shift+O. Use Alt instead of Ctrl on your Mac OS.

The next step is to link the xml to the class file when this activity is created. When an activity is created the onCreate() function on the Activity class is called. So we have to add this inside the onCreate overriding method.

There is no need to write the onCreate function. What you have to do is to select Source>Override/Implement methods.


In the new window select the onCreate(Bundle) and click OK.

Now your class file will be like

public class SecondActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

}

Below the super,onCreate we are going to set the xml file for this activity class. For that use the setContentView(int layoutResID) function. Here layoutResID points the name of your layout file. It should be like R.layout.your_layout_file_name. As my layout file name is second_activity this function will be like setContentView(R.layout.second_activity);

public class SecondActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);
    }

}

Ok. Lets go back to the first activity and implement the button click function now. The name of the button click function I gave in the xml file was 'goToMyNextActivity'. So my function will be like

public void goToMyNextActivity(View view) {
       
    }

We have to implement the navigation to the second activity inside this function. For this as I said earlier we have to use Intent. The steps are

  1. Create an object of Intent.
  2. Initialise it with the current class name and the resulting class name.
  3. start activity using the intent we created.
I will be like 

public void goToMyNextActivity(View view) {
        Intent myIntent;
        myIntent = new Intent(this, SecondActivity.class);
        startActivity(myIntent);
    }

*You can replace those 3 lines with a single line
startActivity(new Intent(this, SecondActivity.class));

I think you understand what it means. Now try to run the project. The first screen will be like



Click the 'Next Activity' button!
What happens now?

The app crashes!! When an android app crashes a 'Force Close' alert will be presented.



Simply click that 'Force close' button. Its time to investigate the reason for the crash :)

For that come back to the eclipse. From Window select show view - Window>Show View>LogCat. You may not see LogCat immediately from the Show View. So select other and search for LogCat. Double click the LogCat for a larger view. It will show the error in RED.



In this place you mouse over the marked line. Now you may know the reason!


The activity is not declared in the AndroidManifest.xml file. So open the AndroidManifest.xml and select the 'Application' view.


Scroll to the bottom. There you can see the Application Nodes. Select 'Add' to add our new activity. In the new alert box that appears select 'Activity'. Now the 'Attributes for Activity' will appear next to the 'Application Nodes'. In the name edit text you have to enter the name of you activity. For that click the 'Browse' button. A new window will appear. Please wait for a moment. The name of the activities will be loaded there.



Click OK save the manifest file and run the app again. This time when you click the 'Next Activity' button the new screen will be shown.


So that's it. You navigated to your second activity!


No comments:

Post a Comment