Lesson 4: Starting Another Activity

After completing the previous lesson, you have an app that shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some code to MainActivity that starts a new activity when the user clicks the Send button.

Respond to the Send Button

In the file res>layout>activity_main.xml, add the android:onClick attribute to the <Button> element as shown below:

<Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/button_send"
      android:onClick="sendMessage" />

This attribute tells the system to call the sendMessage() method in your activity whenever a user clicks on the button.
In the file java>com.example.myfirstapp>MainActivity.java, add the sendMessage() method stub as shown below:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        // Do something in response to button
    }
}

In order for the system to match this method to the method name given to android:onClick, the signature must be exactly as shown. Specifically, the method must:
Be public
Have a void return value
Have a View as the only parameter (this will be the View that was clicked)
Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity.

Build an Intent

An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but in this lesson, your intent starts another activity.

In MainActivity.java, add the code shown below to sendMessage():

public class MainActivity extends AppCompatActivity {
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

Android Studio will display Cannot resolve symbol errors because this code references classes that are not imported. You can solve some of these with Android Studio's "import class" functionality by pressing Alt + Enter (or Option + Return on Mac). Your imports should end up as the following:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

An error remains for DisplayMessageActivity, but that's okay; you'll fix that in the next section.

There’s a lot going on in sendMessage(), so let’s explain what's going on.

The Intent constructor takes two parameters:

A Context as its first parameter (this is used because the Activity class is a subclass of Context)
The Class of the app component to which the system should deliver the Intent (in this case, the activity that should be started).
Note: The reference to DisplayMessageActivity will raise an error in Android Studio because the class doesn’t exist yet. Ignore the error for now; you’ll create the class soon.

The putExtra() method adds the EditText's value to the intent. An Intent can carry data types as key-value pairs called extras. Your key is a public constant EXTRA_MESSAGE because the next activity uses the key to retrive the text value. It's a good practice to define keys for intent extras using your app's package name as a prefix. This ensures the keys are unique, in case your app interacts with other apps.

The startActivity() method starts an instance of the DisplayMessageActivity specified by the Intent. Now you need to create the class.

Create the Second Activity

In the Project window, right-click the app folder and select New>Activity>Empty Activity.
In the Configure Activity window, enter "DisplayMessageActivity" for Activity Name and click Finish
Android Studio automatically does three things:

Creates the class DisplayMessageActivity.java with an implementation of the required onCreate() method.
Creates the corresponding layout file activity_display_message.xml
Adds the required element in AndroidManifest.xml.
If you run the app and click the Send button on the first activity, the second activity starts but is empty. This is because the second activity uses the default empty layout provided by the template.

Display the Message

Now you will modify the second activity to display the message that was passed by the first activity.

In DisplayMessageActivity.java, add the following code to the onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_display_message);

   Intent intent = getIntent();
   String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
   TextView textView = new TextView(this);
   textView.setTextSize(40);
   textView.setText(message);

   ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
   layout.addView(textView);
}

Press Alt + Enter (or Option + Return on Mac) to import missing classes. Your imports should end up as the following:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;

There’s a lot going on here, so let’s explain:

The call getIntent() grabs the intent that started the activity. Every Activity is invoked by an Intent, regardless of how the user navigated there. The call getStringExtra() retrieves the data from the first activity.
You programmatically create a TextView and set its size and message.
You add the TextView to the layout identified by R.id.activity_display_message. You cast the layout to ViewGroup because it is the superclass of all layouts and contains the addView() method.
Note: The XML layout generated by previous versions of Android Studio might not include the android:id attribute. The call findViewById() will fail if the layout does not have the android:id attribute. If this is the case, open activity_display_message.xml and add the attribute android:id="@+id/activity_display_message" to the layout element.

You can now run the app. When it opens, type a message in the text field, and click Send. The second activity replaces the first one on the screen, showing the message you entered in the first activity.

That's it, you've built your first Android app!


You've successfully subscribed to Developer Insider
Great! Next, complete checkout for full access to Developer Insider
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.