Vous êtes sur la page 1sur 27

Faculté Polydisciplinaire de Beni Mellal

Département de Mathématiques et Informatique


Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

TP 3 : Initiation aux activités Android

Introduction

Une activité représente un seul écran dans votre application avec lequel votre utilisateur peut
effectuer une tâche unique et ciblée, comme composer le numéro de téléphone, prendre une
photo, envoyer un courrier électronique ou afficher une carte. Les activités sont généralement
présentées à l'utilisateur sous forme de fenêtres plein écran.

Une application se compose généralement de plusieurs activités qui sont lâchement liés les
uns aux autres. Généralement, une activité d'une application est spécifiée comme activité
"principale", qui est présentée à l'utilisateur au lancement de l'application. Chaque activité
peut alors démarrer d'autres activités afin d'effectuer différentes actions.

Chaque fois qu'une nouvelle activité commence, l'activité précédente est arrêtée, mais le
système conserve l'activité dans une pile (la «back stack»). Quand une nouvelle activité
commence, cette nouvelle activité est poussée sur la pile arrière et prend la priorité de
l'utilisateur. La pile de retour se conforme au mécanisme de pile de base «dernier entré,
premier sorti». Ainsi, lorsque l'utilisateur termine l'activité en cours et appuie sur le bouton
Retour, cette activité est extraite de la pile (et détruite) et l'activité précédente reprend.

Les activités Android sont démarrées ou activées avec les intents. Les intentssont des
messages asynchrones que vous pouvez utiliser dans votre activité pour demander une action
à partir d'une autre activité (ou d'un autre composant d'application). Vous utilisez des intents
pour démarrer une activité à partir d'une autre et pour transmettre des données entre les
activités.

Il y a deux sortes d’intents: explicite et implicite. Une intent explicite est celle dans laquelle
vous connaissez la cible de cette intent, c'est-à-dire que vous connaissez déjà le nom de classe
complet de cette activité spécifique. Une intent implicite est une intent dans laquelle vous
n'avez pas le nom du composant cible mais une action générale à effectuer. Dans ce TP, vous

1
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

apprendrez des intents explicites. Vous découvrirez des intentions implicites dans un TP
ultérieur.

Objectifs:

Vous apprendrez à:

 Créez une nouvelle activité dans Android studio.


 Définir les activités parent et enfant pour la navigation "Up".
 Démarrer des activités avec des intents explicites.
 Passez des données entre les activités avec des « intent extras ».

Tâches à réaliser :
Dans cette pratique, vous allez:

1. Créer une nouvelle application Android avec deux activités.

2. Passer certaines données (une chaîne) de l'activité principale à la seconde en utilisant


une intent, et afficher ces données dans la secondeactivité.

3. Envoyer une deuxième partie de données à l'activité principale, également en utilisant


des intents.

Vue d’ensemble de l’application


Dans ce TP, vous allez créer une application appelée « TwoActivities » qui, sans surprise,
contient deux activités. Cette application sera construite en trois étapes.

Dans la première étape, créez une application dont l'activité principale contient un seul bouton
(Envoyer). Lorsque l'utilisateur clique sur ce bouton, votre activité principale utilise une intent
afin de commencer la deuxième activité.

2
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

Dans la deuxième étape, vous allez ajouter une vue EditText à l'activité principale.
L'utilisateur entre un message et clique sur Envoyer. L'activité principale utilise une intent à la
fois pour démarrer la seconde activité et pour envoyer le message de l'utilisateur à cette
activité. La deuxième activité affiche le message reçu.

3
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

Dans la dernière étape de l'application TwoActivities, ajoutez une vue EditText et un bouton
Reply à la deuxième activité. L'utilisateur peut maintenant taper un message de réponse et
cliquer sur Répondre, et la réponse est affichée sur l'activité principale. À ce stade, utilisez
une intent pour transmettre le message de réponse de la deuxième activité à l'activité
principale.

Tâche 1: Création du projet « TwoActivities »

In this task you'll set up the initial project with a main activity, define the layout, and define a
skeleton method for theonClickbutton event.

1.1 Create the TwoActivities project

1. Start Android Studio and create a new Android Studio project.Call your application "Two
Activities" and change the company domain to "android.example.com." Choose the same
Minimum SDK that you used in the previous projects.

2. Choose Empty Activity for the project template. Click Next.

4
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

3. Accept the default activity name (MainActivity). Make sure the Generate Layout file
box is checked. Click Finish.

5
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

1.2 Define the layout for the main activity

1. Open res/layout/activity_main.xml . In the Layout Editor, click the Text tab at the bottom of
the screen and changethe root view group to RelativeLayout.

 Change the <LinearLayout at the top to <RelativeLayout >


 Scroll down to make sure that the ending tag has also changed to </RelativeLayout> ;
if it hasn't,change it manually.

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.twoactivities.MainActivity">

</RelativeLayout>

2. Click the Design tab at the bottom of the screen and delete the TextView that says "Hello
World."

3. Add a Button to the layout in any position.

4. Switch to the XML Editor (click the Text tab) and modify these attributes in the Button:

6
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

Attribute Value
android:id "@+id/button_main"
android:layout_width wrap_content
android:layout_height wrap_content
android:layout_alignParentRight "true"
android:layout_alignParentBottom "true"
android:layout_alignParentEnd "true"
android:text "Send"
android:onClick "launchSecondActivity"

This may generate an error that "Method launchSecondActivity is missing in MainActivity."


Please ignore this error for now. It will be addressed it in the next task.

5. Place the cursor on the word "Send" .

6. Press Alt-Enter (Option-Enter on the Mac) and select Extract string resources.

7. Set the Resource name to button_mainand click OK.

This creates a string resource in the values/res/string.xml file, and the string in your code is
replaced with a referenceto that string resource.

8. Choose Code > Reformat Code to format the XML code, if necessary (Ctrl +alt+L)

9. Preview the layout of the main activity using the Layout Editor. The layout should look like
this:

7
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

1.3 Define the button action

In this task,you will implement the onClick method you defined in the layout.

1. In the XML Editor, place the cursor on the word "launchSecondActivity" .

2. Press Alt-Enter (Option-Enter on the Mac) and select Create


'launchSecondActivity(View)' in 'MainActivity.

The MainActivity.java files opens, and Android Studio generates a skeleton method for the
onClick handler.

3. Inside launchSecondActivity, add a log statement that says "Button Clicked!"

8
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

Log.d(LOG_TAG, "Button clicked!");

LOG_TAG will show as red. The definitions for that variable will be added in a later step.

4. Place the cursor on the word "Log" and press Alt-Enter (Option-Enter on the Mac).
Android Studio adds an import statement for android.util.Log.

5. At the top of the class, add a constant for the LOG_TAG variable:

private static final String LOG_TAG =MainActivity.class.getSimpleName();

This constant uses the name of the class itself as the tag.

6. Run your app. When you click the "Send" button you will see the "Button Clicked!"
message in the Android Monitor (logcat). If there's too much output in the monitor, type
MainActivity into the search box and the log will only show lines that match that tag.

Tâche 2. Créer et lancer la deuxième activité

Each new activity you added to your project has its own layout and Java files, separate from
those of the main activity. Theyalso have their own <activity>elements in the Android
manifest. As with the main activity, new activities you create in Android Studio also extend
from the AppCompatActivity class.

All the activities in your app are only loosely connected with each other. However, you can
define an activity as a parent of another activity in the AndroidManifest.xml file. This parent-
child relationship enables Android to add navigation hints such as left-facing arrows in the
title bar for each activity.

Activities communicate with each other (both in the same app and across different apps) with
intents. There are two typesof intents, explicit and implicit. An explicit intent is one in which
the target of that intent is known, that is, you already know the fully-qualified class name of
that specific activity. An implicit intent is one in which you do not have the name of thetarget
component, but have a general action to perform. You'll learn about implicit intents in a later
practical.

9
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

In this task you'll add a second activity to our app, with its own layout. You'll modify the
Android manifest to define the main activity as the parent of the second activity. Then you'll
modify the onClickevent method in the main activity to include an intent that launches the
second activity when you click the button.

2.1 Create the second activity

1. Click the app folder for your project and choose File > New > Activity > Empty
Activity.

2. Name the new activity "SecondActivity." Make sure Generate Layout File is checked,
and layout name will be filled in as activity_second.

3. Click Finish. Android Studio adds both a new activity layout (activity_second) and a new
Java file (SecondActivity) to your project for the new activity. It also updates the Android
manifest to include the new activity.

2.2 Modify the Android manifest

1. Open manifests/AndroidManifest.xml .

2. Find the <activity>element that Android Studio created for the second activity.

<activity android:name=".SecondActivity"></activity>

3. Add these attributes to the <activity>element:

10
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

Attribute Value
android:label "Second Activity"
android:parentActivityName ".MainActivity"

The label attribute adds the title of the activity to the action bar.

The parentActivityNameattribute indicates that the main activity is the parent of the second
activity. This parent activity relationship is used for "upward" navigation within your app. By
defining this attribute, the action bar for the second activity will appear with a left-facing
arrow to enable the user to navigate "upward" to the main activity.

4. Place the cursor on "Second Activity" and press Alt-Enter (Option-Enter on the Mac).

5. Choose Extract string resource, name the resource "activity2_name", and click OK.
Android Studio adds a string resource for the activity label.

6. Add a <meta-data>element inside the <activity>element for the second activity. Use these
attributes:

Attribute Value

android:name "android.support.PARENT_ACTIVITY"

android:value "com.example.android.twoactivities.MainActivity"

The <meta-data>element provides additional arbitrary information about the activity as key-
value pairs. In this casethese attributes accomplish the same thing as the
android:parentActivityName attribute -- they define a relationship between two activities for
the purpose of upward navigation. These attributes are required for older versions of Android.
android:parentActivityName is only available for API levels 16 and higher.

2.3 Define the layout for the second activity

1. Open res/layout/activity_second.xmland change the root view group to RelativeLayout, as


you've done in previoustask.

11
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

2. Add a TextView ("Plain Textview" in the Layout Editor). Give the TextView these
attributes:

Attribute Value
android:id "@+id/text_header"
android:layout_width wrap_content
android:layout_height wrap_content
android:text "Message Received"
android:textAppearance "?android:attr/textAppearanceMedium"
android:textStyle "bold"

The value of textAppearance is a special Android theme attribute that defines basic font styles
for small, medium, andlarge fonts. You'll learn more about themes in a later lesson.

3. Extract the "Message Received" string into a resource named text_header.

4. Preview the layout in the Layout Editor. The layout should look like this:

12
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

2.4 Add an intent to the main activity

In this task you'll add an explicit intent to the main activity. This intent is used to activate the
second activity when the Send button is clicked.

1. Open the Java file for MainActivity


(java/com.example.android.twoactivities/MainActivity).

2.Create a new intent in the launchSecondActivity()method.

The Intent constructor takes two arguments for an explicit intent: an application
Context and the specific componentthat will receive that intent. Here you should use
thisas the context, and SecondActivity.classas the specific class.

13
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

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

3. Place the cursor on Intent and press Alt-Enter (Option-Enter on the Mac) to add an
import for the Intent class.

4. Call the startActivity() method with the new intent as the argument.

startActivity(intent);

5. Run the app.

When you click the Send button the main activity sends the intent and the Android
system launches the secondactivity. That second activity appears on the screen. To
return to the main activity, click the Android Back button at the bottom left of the
screen, or you can use the left arrow at the top of the second activity to return to the
main activity.

Travail à faire 1:

What happens if you remove the android:parentActivityNameand the <meta-data>elements


from themanifest? Make this change and run your app.

Tâche 3. Envoyer des données depuis l’activé principale vers la deuxième activité

In the last task, you added an explicit intent to the main activity that activated the second
activity. You can also use intents to send data from one activity to another.

In this task, you'll modify the explicit intent in the main activity to include additional data (in
this case, a user-entered string)in the intent extras. You'll then modify the second activity to
get that data back out of the intent extras and display it on thescreen.

3.1 Add an EditText to the main activity layout

1. Open res/layout/activity_main.xml.

2. Add an EditText view (Plain Text in the Layout Editor.) Give the EditText these attributes:

Attribute Value

14
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

android:id "@+id/editText_main"

android:layout_width match_parent

android:layout_height wrap_content

android:layout_toLeftOf "@+id/button_main"

android:layout_toStartOf "@+id/button_main"

android:layout_alignParentBottom "true"

android:hint "Enter Your Message Here"

3. Delete the android:text attribute.

4. Extract the "Enter Your Message Here" string into a resource named editText_main.

The new layout for the main activity looks like this:

15
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

3.2 Add a string to the main activity's intent extras

Your intent object can pass data to the target activity in two ways: in the data field, or in the
intent extras. The intent's datais a URI indicating the specific data to be acted on. If the
information you want to pass to an activity through an intent is not a URI, or you have more
than one piece of information you want to send, you can put that additional information into
the intent extras instead.

The intent extras are key/value pairs in a Bundle. A bundle is a collection of data, stored as
key/value pairs. To pass information from one activity to another, you put keys and values
into the intent extra bundle from the sending activity, and then get them back out again in the
receiving activity.

16
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

1. Open java/com.example.android.twoactivities/MainActivity .

2. Add a public constant at the top of the class to define the key for the intent extra:

public static final String EXTRA_MESSAGE =

"com.example.android.twoactivities.extra.MESSAGE";

3. Add a private variable at the top of the class to hold the EditText object. Import the
EditText class.

private EditText mMessageEditText;

4. In the onCreate() method, use findViewByID to get a reference to the EditText instance and
assign it to that private variable:

mMessageEditText = (EditText) findViewById(R.id.editText_main);

5. In the launchSecondActivity() method, just under the new intent, get the text from the
EditText as a string:

String message = mMessageEditText.getText().toString();

6. Add that string to the intent as an extra with the EXTRA_MESSAGE constant as the key
and the string as the value:

intent.putExtra(EXTRA_MESSAGE, message);

3.3 Add a TextView to the second activity for the message

1. Open res/layout/activity_second.xml .

2. Add a second TextView. Give the TextView these attributes:

<TextView
android:id="@+id/text_message"
android:layout_width="wrap_content"

17
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

android:layout_height="wrap_content"
android:layout_below="@+id/text_header"
android:layout_marginLeft="200dip"
android:layout_marginStart="100dip"
android:textAppearance="?android:attr/textAppearanceMedium" />

The new layout for the second activity looks the same as it did in the previous task, because
the new TextView does not(yet) contain any text, and thus does not appear on the screen.

3.4 Modify the second activity to get the extras and display the message

1. Open java/com.example.android.twoactivities/SecondActivity .

2. In the onCreate() method, get the intent that activated this activity:

Intent intent = getIntent();

3. Get the string containing the message from the intent extras using the
MainActivity.EXTRA_MESSAGE static variable as the key:

String message =

intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

4. Use findViewByID to get a reference to the TextView for the message from the layout (you
may need to import the TextView class):

TextView textView = (TextView) findViewById(R.id.text_message);

5. Set the text of that TextView to the string from the intent extra:

textView.setText(message);

6. Run the app. When you type a message in the main activity and click Send, the second
activity is launched and displays that message.

public void launchSecondActivity(View view) {

Log.d(LOG_TAG, "Button clicked!");


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

18
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

String message = mMessageEditText.getText().toString();


intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}

Tâche 4 : Retourner les données à l'activité principale

Now that you have an app that launches a new activity and sends data to it, the final step is to
return data from the secondactivity back to the main activity. You'll also use intents and intent
extras for this task.

4.1 Add an EditText and a Button to the second activity layout

1. Copy the EditText and Button from the main activity layout file and paste them into the
second layout.

2. In the activity_second.xml file, modify the attribute values for both the Button and EditText
views. Use these values:

Old attribute (Button) New attribute (Button)

android:id="@+id/button_main" android:id="@+id/button_second"

android:onClick= "launchSecondActivity" android:onClick="returnReply"

android:text= "@string/button_main" android:text= "@string/button_second"

Old attribute (EditText) New attribute (EditText)

android:id="@+id/editText_main" android:id="@+id/editText_second"

android:layout_toLeftOf= "@+id/button_main" android:layout_toLeftOf= "@+id/button_second"

android:layout_toStartOf= "@+id/button_main" android:layout_toStartOf= "@+id/button_second"

android:hint= "@string/editText_main" android:hint= "@string/editText_second"

19
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

3. Open res/values/strings.xml and add string resources for the button text and the hint in the
EditText:

<string name="button_second">Reply</string>

<string name="editText_second">Enter Your Reply Here</string>

4. In the XML layout editor, place the cursor on "returnReply" , press Alt-Enter (Option-
Enter on the Mac) and select

Create 'launchSecondActivity(View)' in 'SecondActivity'.

The SecondActivity.java files open, and Android Studio generates a skeleton method for the
onClick handler. You will

implement this method in the next task.

The new layout for the second activity looks like this:

20
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

4.2 Create a response intent in the second activity

1. Open java/com.example.android.twoactivities/SecondActivity .

2. At the top of the class, add a public constant to define the key for the intent extra:

public static final String EXTRA_REPLY ="com.example.android.twoactivities.extra.REPLY";

3. Add a private variable at the top of the class to hold the EditText object.

private EditText mReply;

4. In the onCreate() method, use findViewByID() to get a reference to the EditText instance
and assign it to that privatevariable:
21
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

mReply = (EditText) findViewById(R.id.editText_second);

5. In the returnReply() method, get the text of the EditText as a string:

String reply = mReply.getText().toString();

6. Create a new intent for the response.

Note: Do not reuse the intent object you received from the original request. Create a new
intent for the response.

Intent replyIntent = new Intent();

7. Add the reply string from the EditText to the new intent as an intent extra. Since extras are
key/value pairs, here the key is EXTRA_REPLY and the the value is the reply:

replyIntent.putExtra(EXTRA_REPLY, reply);

8. Set the result to RESULT_OK to indicate the response was successful. Result codes
(including RESULT_OK and RESULT_CANCELLED) are defined by the Activity class.

setResult(RESULT_OK,replyIntent);

9. Call finish()to close the activity and return to the main activity.

finish();

22
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

4.3 Add TextViews to the main activity layout to display the reply

The main activity needs a way to display the reply sent back from the second activity. In this
task you'll add TextViews to themain activity layout to display that reply. To make this easier,
you will copy the TextViews you used in the second activity.

1. Copy the two TextViews for the message display from the second activity layout file and
paste them into the main layout above the existing EditText and Button views.

2. Modify the attribute values for both of these new TextViews. Use these values:

Old attribute (header TextView) New attribute (header TextView)

android:id="@+id/text_header" android:id="@+id/text_header_reply"

android:text="@string/text_header" android:text= "@string/text_header_reply"

Old attribute (message TextView) New attribute (message TextView)

android:id="@+id/text_message" android:id="@+id/text_message_reply"

android:layout_below= "@+id/text_header" android:layout_below= "@+id/text_header_reply"

3. Add the android:visibilityattribute to each of the TextViews to make them initially


invisible. (Having them visible onthe screen, but without any content, can be confusing to the
user.) You will make these TextViews visible after the response data is passed back from the
second activity.

android:visibility="invisible"

4. Open res/values/strings.xml and add a string resource for the reply header:

<string name="text_header_reply">Reply Received</string>

23
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

The layout for the main activity looks the same as it did in the previous task--although you
have added two new TextViews to the layout. However, since you set the TextViews to
invisible, they do not appear on the screen.

4.4 Get the reply from the intent extra and display it

When you use an explicit intent to start another activity, you may not expect to get any data
back -- you're just activatingthat activity. In that case, you use startActivity() to start the new
activity, as you did earlier in this lesson. If you want to get data back from the activated
activity, however, you'll need to start it with startActivityFromResult().

In this task you'll modify the app to start the second activity and expect a result, to extract that
return data from the intent,and to display that data in the TextViews you created in the last
task.

1. Open java/com.example.android.twoactivities/MainActivity.

2. Add a public constant at the top of the class to define the key for a particular type of
response you're interested in:

public static final int TEXT_REQUEST = 1;

3. Add two private variables to hold the reply header and reply TextViews:

private TextView mReplyHeadTextView;

private TextView mReplyTextView;

4. In the onCreate() method, use findViewByID to get references from the layout to the reply
header and reply TextView. Assign those view instances to the private variables:

mReplyHeadTextView = (TextView) findViewById(R.id.text_header_reply);

mReplyTextView = (TextView) findViewById(R.id.text_message_reply);

5. In the launchSecondActivity() method, modify the call to startActivity( ) to be


startActivityForResult() , and include the TEXT_REQUEST key as an argument:

startActivityForResult(intent, TEXT_REQUEST);

24
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

6. Create the onActivityResult() callback method with this signature:

public void onActivityResult(int requestCode, int resultCode,Intent data)

{}

7. Inside onActivityResult(), call super.onActivityResult() :

super.onActivityResult(requestCode, resultCode, data);

8. Add code to test for both TEXT_REQUEST (to process the right intent result, in case there
are multiple ones) and the RESULT_CODE (to make sure the request was successful):

if (requestCode == TEXT_REQUEST) {

if (resultCode == RESULT_OK) {

9. Inside the inner if block, get the intent extra from the response intent ( data ). Here the key
for the extra is theEXTRA_REPLY constant from SecondActivity:

String reply = data.getStringExtra(SecondActivity.EXTRA_REPLY);

10. Set the visibility of the reply header to true:

mReplyHeadTextView.setVisibility(View.VISIBLE);

11. Set the reply textview text to the reply, and set its visibility to true:

mReplyTextView.setText(reply);

mReplyTextView.setVisibility(View.VISIBLE);

12. Run the app.

Now, when you send a message to the second activity and get a reply back, the main activity
updates to display the reply.

public void onActivityResult(int requestCode, int resultCode,


Intent data) {

25
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

super.onActivityResult(requestCode, resultCode, data);


if (requestCode == TEXT_REQUEST) {
if (resultCode == RESULT_OK) {
String reply =
data.getStringExtra(SecondActivity.EXTRA_REPLY);
mReplyHeadTextView.setVisibility(View.VISIBLE);
mReplyTextView.setText(reply);
mReplyTextView.setVisibility(View.VISIBLE);
}
}
}

26
Faculté Polydisciplinaire de Beni Mellal
Département de Mathématiques et Informatique
Module : Programmation Mobile
Master STRI
Année universitaire : 2019/2020 Pr. Yassine SADQI

Travail à faire 2

Créer une application avec trois boutons: Texte un, texte deux et texte trois. Lorsque l'un de
ces boutons est cliqué, lancez une deuxième activité. Cette deuxième activité devrait contenir
un ScrollView qui affiche l'un des trois passages de texte (vous pouvez inclure votre choix de
passages). Utilisez les intents pour lancer la seconde activité et les extras d’intent pour
indiquer lequel des trois passages à afficher.

27