Starting Another Activity

Whats up Geeks,

After learning from our previous tutorials we are now enough capable to launch another Activity from one Activity.

In this tutorial we are going to do this by a button click. We are going to define another Activity when a button is clicked.

We are going to define an app that shows 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. On  Button click we are going to perform DisplayMessageActivity displaying the message from first Screen.

Respond to the Send Button

In order to respond to the button's on-click event, open the fragment_main.xml layout file and add the android:onClick attribute to the <Button> element:
 
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />
 
The android:onClick attribute’s value, "sendMessage", is the name of a method in our activity that the system calls when the user clicks the button.

Now we open the MainActivity class (located in the project's src/ directory) and add the corresponding method:

/** 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, we’ll fill in this method to read the contents of the text field and deliver that text to another activity.

Now 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." We can use intents for a wide variety of tasks, but most often they’re used to start another activity.
Inside the sendMessage() method, create an Intent to start an activity called
DisplayMessageActivity:

Intent intent = new Intent(this, DisplayMessageActivity.class);
 
This requires that us import the Intent class:
 
import android.content.Intent;

Tip: In Eclipse, press Ctrl + Shift + O to import missing classes (Cmd + Shift + O on Mac).
The constructor used here 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)
An intent not only allows us to start another activity, but it can carry a bundle of data to the activity as well. Inside the sendMessage() method, use findViewById() to get the EditText element and add its text value to the intent:

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);
 
 
In order for the next activity to query the extra data, we should define the key for our intent's extra using a public constant. So add the EXTRA_MESSAGE definition to the top of the MainActivity class:

public class MainActivity extends ActionBarActivity {
    public final static String EXTRA_MESSAGE = "in.geeksandroids.hello.MESSAGE";
    ...
}
 
It's generally a good practice to define keys for intent extras using our app's package name as a prefix. This ensures they are unique, in case our app interacts with other apps.

Coming down next question is how to start the second Activity?
To start an activity, call startActivity() and pass it our Intent. The system receives this call and starts an instance of the Activity specified by the Intent.

With this new code, the complete sendMessage() method that's invoked by the Send button now looks like this:

/** 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);
}
Now we need to create the DisplayMessageActivity class in order for this to work.

How to create the second Activity?

Below steps let us know how to create the second Activity:

To create a new activity using Eclipse:
  1. Click New in the toolbar.
  2. In the window that appears, open the Android folder and select Android Activity. Click Next.
  3. Select BlankActivity and click Next.
  4. Fill in the activity details:
    • Project: Hello
    • Activity Name: DisplayMessageActivity
    • Layout Name: activity_display_message
    • Fragment Layout Name: fragment_display_message
    • Title: My Message
    • Hierarchial Parent: in.geeksandroids.hello.MainActivity
    • Navigation Type: None
    Click Finish.
The DisplayMessageActivity class should now look like this:
 
public class DisplayMessageActivity extends ActionBarActivity {

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() { }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                  Bundle savedInstanceState) {
              View rootView = inflater.inflate(R.layout.fragment_display_message,
                      container, false);
              return rootView;
        }
    }
}
If we used an IDE other than Eclipse, update our DisplayMessageActivity class with the above code.

Add the title string

If we used Eclipse, we can skip to the next section, because the template provides the title string for the new activity.
If we're using an IDE other than Eclipse, add the new activity's title to the strings.xml file:
<resources>
    ...
    <string name="title_activity_display_message">My Message</string>
</resources>

Add it to the manifest

All activities must be declared in our manifest file, AndroidManifest.xml, using an <activity> element.
When we use the Eclipse tools to create the activity, it creates a default entry. If we're using a different IDE, we need to add the manifest entry yourself. It should look like this:
<application ... >
    ...
    <activity
        android:name="in.geeksandroids.hello.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="in.geeksandroids.hello.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="in.geeksandroids.hello.MainActivity" />
    </activity>
</application>


Receive the Intent

In the DisplayMessageActivity class’s onCreate() method, get the intent and extract the message delivered by MainActivity:

Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 
 

Display the Message

To show the message on the screen, create a TextView widget and set the
text using setText(). Then add the TextView as the root view of the activity’s layout by passing it to setContentView().
The complete onCreate() method for DisplayMessageActivity now looks like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    // Set the text view as the activity layout
    setContentView(textView);
}

We can now run the app. When it opens, type a message in the text field, click Send, and the message appears on the second activity.

That's all Geeks, see ya in the next tutorial with some new learnings.


No comments:

Post a Comment