In the next steps, you will add an empty activity and use it as the start activity. From this start activity, the user can navigate to the main activity and other activities such as map activity and street view activity.
1. Add an Empty activity to the project as follows
Right click on the first package (com.example.mobiletechapp) in the java folder.
Select New then Activity and then Empty Activity.
Enter StartActivity to the Activity Name text box.
The language is Java. Click Finish.
2. Open activity_start.xml, add a button to the layout and set id to buttonUIEvent, text to UI and Events, layout_width to 0dp, top constraint to 32dp, left constraint to 100dp and right constraint to 100dp as follows
Navigate from the start activity to the main activity
3. Open StartActivity.java and add the following click event listener
public void openMainActivity(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
The Intent class is used to create an instance with the current activity (this) and the main activity (MainActivity.class). The startActivity method is then called to perform the navigation.
4. Back to activity_start.xml, find onClick in the attributes list and select openMainActivity.
5. If you run the project now, you will see the main activity on the emulator. To make the app start with the start activity (not the main activity), open AndroidManifest.xml, and swap the activity names as follows.
6. Run your project and you will see the start activity on the emulator. Click the button and the app will navigate you to the main activity.
Send data from the start activity to the main activity
In the next steps, you will send the text Hello World! from the start activity to the main activity and replace the current text Mobile Technologies with it.
7. Open StartActivity.java and add the following line intent.putExtra("message", "Hello World!"); to the openMainActivity click event listener as follows
public void openMainActivity(View view) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("message", "Hello World!");
startActivity(intent);
}
The text Hello World! is a value of the string message.
Open MainActivity.java, add the following code to the onCreate method to get the value (that is Hello World!) of the string message then assign this value to the string variable msg, and then set text of the textViewOutput element to it.
8. Run the project and click the button. You will see Hello World! instead of Mobile Technologies.