Android Development #9

Build an Intent

Divyendra Rajawat
2 min readMar 27, 2021
Photo by Pathum Danthanarayana on Unsplash

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 fora a wide varity of tasks, but in this lesson, your intent starts another activity.

In MainActivity, add the EXTRA_MESSAGE constant and the sendMessage(), code, as shown:

public class MainActivity extends AppCompatActivity {
public static final 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 taps the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}

Expect Android Studio to encounter Cannot resolve symbol errors again. To clear the errors, press Alt+Enter, or Option+Return on a Mac. Your should end up with the following imports:

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

An error still remains for DisplayMessageActivity, but that’s okay. You fix it in the next section.

here’s what’s going in sendMessage():

  • The intent constructor takes two parameters, a context and a class.

The context parameter is used first because the Activity class is a subclass of Context.

The class parameter of the app of component, to which the system delivers the intent, is, in this case, the activity to start.

  • The putExtra() method adds the value of EditText to the intent. An Intent can carry data types as key-values pairs called extras.

Your key is a public constant EXTRA_MESSAGE because the next activity uses the key to retrieve the text value. It’s a good practice to define keys for intent extras with your app’s package name as a prefix. This ensures that the keys are unique, in case your app interacts with other apps.

  • The startActivity() method starts an instance of the DisplayMessageActivity that’s specified by the intent. Next, you need to create that class.

Note: The Navigation Architecture Component allows you to use the Navigation Editor to associate one activity with another. Once the relationship is made, you can use API to start the second activity when the user triggers the associated action, such as when the user clicks a button.

--

--