Reader small image

You're reading from  Android Studio 4.2 Development Essentials - Java Edition

Product typeBook
Published inAug 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781803238814
Edition1st Edition
Languages
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor's degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

53. Android Explicit Intents – A Worked Example

The chapter entitled “An Overview of Android Intents” covered the theory of using intents to launch activities. This chapter will put that theory into practice through the creation of an example application.

The example Android Studio application project created in this chapter will demonstrate the use of an explicit intent to launch an activity, including the transfer of data between sending and receiving activities. The next chapter (“Android Implicit Intents – A Worked Example”) will demonstrate the use of implicit intents.

53.1 Creating the Explicit Intent Example Application

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Empty Activity template before clicking on the Next button.

Enter ExplicitIntent into the Name field and specify com.ebookfrenzy.explicitintent as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java. Using the steps outlined in section 11.8 Migrating a Project to View Binding, convert the project to use view binding.

53.2 Designing the User Interface Layout for MainActivity

The user interface for MainActivity will consist of a ConstraintLayout view containing EditText (Plain Text), TextView and Button views named editText1, textView1 and button1 respectively. Using the Project tool window, locate the activity_main.xml resource file for MainActivity (located under app -> res -> layout) and double-click on it to load it into the Android Studio Layout Editor tool. Select and delete the default “Hello World!” TextView.

Drag a TextView widget from the palette and drop it so that it is centered within the layout and use the Attributes tool window to assign an ID of textView1.

Drag a Button object from the palette and position it so that it is centered horizontally and located beneath the bottom edge of the TextView. Change the text property so that it reads “Send Text” and configure the onClick property to call a method named sendText.

Next, add a Plain Text...

53.3 Creating the Second Activity Class

When the “Send Text” button is touched by the user, an intent will be issued requesting that a second activity be launched into which a response can be entered by the user. The next step, therefore, is to create the second activity. Within the Project tool window, right-click on the com.ebookfrenzy.explicitintent package name located in app -> java and select the New -> Activity -> Empty Activity menu option to display the New Android Activity dialog as shown in Figure 53-3:

Figure 53-3

Enter SecondActivity into the Activity Name and Title fields and name the layout file activity_second and change the Language menu to Java. Since this activity will not be started when the application is launched (it will instead be launched via an intent by MainActivity when the button is pressed), it is important to make sure that the Launcher Activity option is disabled before clicking on the Finish button.

53.4 Designing the User Interface Layout for SecondActivity

The elements that are required for the user interface of the second activity are a Plain Text EditText, TextView and Button view. With these requirements in mind, load the activity_second.xml layout into the Layout Editor tool, and add the views.

During the design process, note that the onClick property on the button view has been configured to call a method named returnText, and the TextView and EditText views have been assigned IDs textView2 and editText2 respectively. Once completed, the layout should resemble that illustrated in Figure 53-4. Note that the text on the button (which reads “Return Text”) has been extracted to a string resource named return_text.

With the layout complete, click on the Infer constraints toolbar button to add the necessary constraints to the layout:

Figure 53-4

53.5 Reviewing the Application Manifest File

In order for MainActivity to be able to launch SecondActivity using an intent, it is necessary that an entry for SecondActivity be present in the AndroidManifest.xml file. Locate this file within the Project tool window (app -> manifests), double-click on it to load it into the editor and verify that Android Studio has automatically added an entry for the activity:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.ebookfrenzy.explicitintent">

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

    ...

53.6 Creating the Intent

The objective for MainActivity is to create and start an intent when the user touches the “Send Text” button. As part of the intent creation process, the question string entered by the user into the EditText view will be added to the intent object as a key-value pair. When the user interface layout was created for MainActivity, the button object was configured to call a method named sendText() when “clicked” by the user. This method now needs to be added to the MainActivity class MainActivity.java source file as follows:

package com.ebookfrenzy.explicitintent;

.

.

import android.content.Intent;

.

.

public class MainActivity extends AppCompatActivity {

.

.

    public void sendText(View view) {

 

        Intent i = new Intent(this, SecondActivity.class);

 

        String myString...

53.7 Extracting Intent Data

Now that SecondActivity is being launched from MainActivity, the next step is to extract the String data value included in the intent and assign it to the TextView object in the SecondActivity user interface. This involves adding some code to the onCreate() method of SecondActivity in the SecondActivity.java source file in addition to adapting the activity to use view binding:

package com.ebookfrenzy.explicitintent;

 

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.content.Intent;

import android.view.View;

 

import com.ebookfrenzy.explicitintent.databinding.ActivitySecondBinding;

 

public class SecondActivity extends AppCompatActivity {

 

    private ActivitySecondBinding binding;

 

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState...

53.8 Launching SecondActivity as a Sub-Activity

In order for SecondActivity to be able to return data to MainActivity, SecondActivity must be started as a sub-activity of MainActivity. This means that the call to startActivity() in the MainActivity returnText() method needs to be replaced with a call to startActivityForResult(). Unlike the startActivity() method, which takes only the intent object as an argument, startActivityForResult() requires that a request code also be passed through. The request code can be any number value and is used to identify which sub-activity is associated with which set of return data. For the purposes of this example, a request code of 5 will be used, giving us a modified MainActivity class that reads as follows:

public class MainActivity extends AppCompatActivity {

              

    private static final int request_code = 5;

.

.

  ...

53.9 Returning Data from a Sub-Activity

SecondActivity is now launched as a sub-activity of MainActivity, which has, in turn, been modified to handle data returned from SecondActivity. All that remains is to modify SecondActivity.java to implement the finish() method and to add code for the returnText() method, which is called when the “Return Text” button is touched. The finish() method is triggered when an activity exits (for example when the user selects the back button on the device):

public void returnText(View view) {

              finish();

}

 

@Override

public void finish() {

       Intent data = new Intent();

 

       String returnString = binding.editText2.getText().toString();

       data.putExtra("returnData", returnString);

 ...

53.10 Testing the Application

Compile and run the application, enter a question into the text field on MainActivity and touch the “Send Text” button. When SecondActivity appears, enter the text to the EditText view and use either the back button or the “Return Text” button to return to MainActivity where the response should appear in the text view object.

53.11 Summary

Having covered the basics of intents in the previous chapter, the goal of this chapter was to work through the creation of an application project in Android Studio designed to demonstrate the use of explicit intents together with the concepts of data transfer between a parent activity and sub-activity.

The next chapter will work through an example designed to demonstrate implicit intents in action.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.2 Development Essentials - Java Edition
Published in: Aug 2021Publisher: PacktISBN-13: 9781803238814
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor's degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth