Intents

To start a new Activity we use an Intent. Intents are messaging objects which means that they can also be used to pass data from one Activity to another. Intents also have other uses such as starting different types of app components including components from other applications, e.g. composing a new email. In this course intents will only be used to start a new Activity in the same app. In the example below an intent is created, the name Daniel and number 1 is attached and the intent is used to start SecondActivity.

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("name", "Daniel"); // Optional
intent.putExtra("number", 1); // Optional
startActivity(intent);

Normally no action is needed to handle the intent in the SecondActivity. However, if there are attached data as the case name and number above, that data is made available from the intent in the form of a Bundle.

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String name = extras.getString("name");
    int number = extras.getInt("number");
    // Do something with the name and number
}

VIDEO

Last updated

Was this helpful?