Вы находитесь на странице: 1из 25

“Introduction to Mobile Application Development Using Android”

Week Two Video Lectures

Week Two: Activity Lifecycle and UI


Lecture 1: Android App Structure
Unit 1: Android App Structure

So far, we have seen two different applications-- the HelloWorld and the GreetFriend application.
Both of these applications contained a single activity.

Now, in general, Android applications could be composed of several components. It could contain
several different activities, one or more services, broadcast receivers, and perhaps content
providers.

The structure of a specific application depends on how it is designed and what components it is
designed to contain. The details of the components that form part of an application is contained in
a file called the Android Manifest file.

Every single application contains at least one or more manifest files. Let's look at an example of a
manifest file for our GreetFriend application.

So, in this manifest file, as you can notice, the first thing that you see is that it is a XML file. It
contains several different pieces of information. In particular, let me draw your attention to the
description of the activity that is contained within this manifest file. It provides various properties
related to this activity.

So, in general, applications declare their components in a manifest file. So, if your application
contains several activities, or maybe services, each one of them will have to be declared inside this
manifest file. The manifest file is included as part of the apk package.

So, the Android framework consults your manifest file in order to learn which components are
part of your application and the specific details about each of those components.

So, as you saw, the manifest file is a structured XML file. And it contains several details related to
your application, including any API libraries that your application may involve. In addition, later on
we will see that if your application requires certain permissions, then these have to be declared in
the manifest file.

In general, an application consists of one or more activities. Now, as we have already learned,
every activity is associated with its corresponding user interface. Now if your application contains
multiple activities, one of them will be designated as the main activity that is the activity that will
be started when your application first launches.

Now moving from one activity to another activity involves having the current activity start the next
one. There is a mechanism called as Intent that allows you to start new components within your
application. We will examine the details of our Intents in the next exercise.

So, let's move on to the next exercise where we will introduce an additional activity to our
GreetFriend application.

Week 2: Introduction to Mobile Application Development Using Android 1


Now we'll modify the GreetFriend application such that we have one activity where it seeks the
user's input of his or her friend's name. And when the button is clicked, the application will move
to a second activity, which displays the greeting message.

Now, to start the second activity from the first activity, we will use the Intent mechanism for this
purpose. We will learn more details about Intents and how we make use of them in the next
exercise.

Week 2: Introduction to Mobile Application Development Using Android 2


Week Two: Activity Lifecycle and UI
Lecture 1: Android App Structure
Unit 4: Exercise Greet Friend (with Activity)

This is a pattern that we have already seen earlier. In order to obtain the reference to the
TextView, so we'll say findViewById.

We have already given this an IDS textMessage. So, once we complete that, all that I need to do
next is to say textMessage, setText, and supply message as the parameter.

In this exercise, we are going to continue modifying the GreetFriend application that we developed
in the previous exercise.

Starting with the GreetFriend application that we developed, we are now going to modify the
GreetFriend application such that the user inputs his friend's name on one screen and when the
button is clicked, then the application will move to a second activity that will display the greeting
string on the screen in a different activity.

Now, to go ahead and do this modification to the GreetFriend application, let's start with the
current state of the application.

We're going to go in and modify the activity_main.xml file. We will remove this Hello World
TextView from the user interface because we are no longer going to need that in the extension of
this exercise.

So, let's delete that Hello World from there. We are now going to add a new activity to this
application. To do that, go right there and then right-click and say New Activity, Blank Activity. And
when the window opens, type in the new name of the activity as ShowMessage and click on Finish.

Now, once the Android Studio goes through with its construction, it'll come up with the new
activity call ShowMessage where it'll fill in some basic template code and then also create this new
layout for the new activity that we just added called ShowMessage. And correspondingly, the
activity layout file will be called activity_show_message.xml.

Now let's go into this activity and then modify this user interface so that the Hello World string
which is now a TextView is going to be positioned at the center and slightly below. We have
already seen how to do this in the previous exercises.

In addition, we are going to modify the text size to be 24 points, just like what we did in the
previous exercises. So, we'll go in and in the properties, type in 24sp. And double-click on the
string and give the ID to this as Text Message.

Note that we had removed the TextView from the previous layout for the main activity, which was
also named Text Message, and instead we are now inserting a TextView in this new layout and
giving it the same ID.

So, the order in which we do this is important. We first remove the TextView from
activity_main.xml. Then add the new activity called ShowMessage, and then go in and edit the user
interface, and then give the TextView the same ID as we used before for the other TextView.

Week 2: Introduction to Mobile Application Development Using Android 3


Once we have completed this part, let's go ahead and then modify the code in order to activate
the new activity. And in order to move from the main activity to the ShowMessage activity when
the user clicks on the greetings button.

Let's now switch to MainActivity.Java file. Now, in this file, we saw that we were setting the
textMessage text string value to the greeting that we displayed together with the friend's name.

Now we have removed that TextView from the UI of the main activity and instead are going to use
the TextView of the ShowMessage activity in order to display the greeting. The basic flow of the
app will remain the same until the user clicks the Greetings button.

When the user clicks the Greetings button, we are now going to cause a switch from the
MainActivity to the ShowMessage activity. Indeed, when the user clicks on the Greet button, we're
going to start the ShowMessage activity and then display the greeting string in the user interface
for the ShowMessage activity.

To do that, first and foremost we need to learn how we can start a new activity from the current
activity. To help us do that, we'll go into the code here and then we will edit the code and say
Intent and equal to new Intent, and we'll say this and ShowMessage.class.

Now, this is the procedure for declaring and creating an intent. An intent is a message-passing
mechanism that is built into Android that enables you to pass messages from one component to
another component through the Android framework.

We will examine intents and its details in greater length in one of the later discussions. Now again,
let's import the library for intent.

Now, this is the way we will declare an intent. Now if we need to start a new activity, we will take
this intent and then we are supposed to say startActivity () and supply the intent.

Now, this is how we will start a new activity from the current activity. Now, between these two
statements, there is that message string that we just constructed and then pass it to set the
textMessage TextView.

Now, we have to pass this string to the new activity =so that the new activity will display this string
in the TextView on its UI layout. So, to do that, we need to replace this statement by appropriately
modifying it.

Android allows intents to carry additional information from one activity to another activity. So
essentially intent, as I mentioned, is a message-passing mechanism. It will also carry some payload
along with it.

So, to do so, we are going to pass this string that we just constructed over to the ShowMessage
activity through adding some extra payload to this intent.

In order to pass the string from the current activity to the next activity, you're going to take the
help of a method called as putExtra that is part of the intent class. So, we'll say intend putExtra,
and we will specify a string name here.

Week 2: Introduction to Mobile Application Development Using Android 4


So, we will just say Message. The reason why we use the first-string name is that when you pass
this intent to the second activity, when the second activity gets started, it will have access to the
same intent and it can then retrieve the information that we send through this intent from the
current activity to the next activity.

So, the putExtra is a method of passing information from one activity to another activity, using the
intent to carry it as a payload. Now here we are going to move this particular string that we
constructed, the message string, and then add it in as a parameter to this putExtra, and then we're
going to delete this textMessage statement here.

So, we have now modified the MainActivity.java such that when the Greet button is clicked, it will
result in the creation of an intent. The intent will carry the greeting string as its payload, and then
we're going to pass this intent to the Android framework by calling startActivity method of the
Android framework.

Now, when the startActivity method is called, the Android framework will in turn then go ahead
and start the new activity. The new activity is specified in the intent here as ShowMessage.class.

So, we have completed the modification to the MainActivity.java, let's go ahead and save this
modification, and we will switch to the ShowMessage.java class. When you go to the
ShowMessage.java class, now when this activity gets created, obviously, you realize that the
onCreate method of this activity is going to called.

So, we are going to go into the onCreate method of this ShowMessage activity. And in here, we can
see intent in, and say getIntent. So, this is a way of obtaining the intent that started this activity.

Again, when you see the red line, import the appropriate by holding the Alt-Enter or Option-Enter
depending on whether you're using Windows or a Mac machine. Now, once you obtain the intent,
we will now be able to extract the string message that came in.

So, I will now say String message and I will say in and here we are going to specify it as in
getStringExtra. And then the parameter to the getStringExtra method would be the exact same
string that we used in the MainActivity.java. In the MainActivity.java, we used the string as
message.

So, I'm going to use the same string here, and then specify it here. This is the way for extracting
the string that came in as the payload in the intent object.

Now, once we have obtained the message, now we can go ahead and then set the TextView on the
user interface to the message that we just obtained. So, to do that, we will go in and say TextView.

Now, this completes the modification to the ShowMessage.java file. And so now the ShowMessage
activity will be able to obtain the message string that was passed to it from the MainActivity.java
file. So, let's go ahead and save this, and then run this app.

Once the app starts running on the emulator or if you're using a device, it'll be shown on the
screen of your device. You now see the modified user interface for the GreetFriend application.

Week 2: Introduction to Mobile Application Development Using Android 5


Let's go ahead and type in our friend’s name, say John, and then click on the Greetings button. And
then you would notice that when you click on the Greetings button, the app now switches from the
MainActivity to the ShowMessage activity. And in the ShowMessage activity, we are displaying the
message as Good Day, John!

With this, we complete this exercise where we have seen how we can introduce a new activity into
our app and how we can start one activity from another activity by using an intent.

And also, we have seen how we can pass information from one activity to another activity using
the payload facility that is available within the intent.

So, you are going to use the putExtra in the first activity to add to the information to the intent.
And in the second activity, you're going to use the getExtra methods to retrieve the information
from the intent.

Week 2: Introduction to Mobile Application Development Using Android 6


Week Two: Activity Lifecycle and UI
Lecture 2: Android Activity Intents
Unit 1: Android Activity Intents

Next, we will get a quick overview of intents. We have already seen intents being used in the
GreetFriend example in the previous exercise. So, what we have learned so far is that intents
are a way of starting Android components.

So, for example, if you want to start an activity from the current activity or if you want to start a
service or invoke a broadcast receiver, you will make use of the intent mechanism to start
them up. And we have seen the example of how we start the ShowMessage activity from the
MainActivity in the GreetFriend application.

Content providers are a different kind of component altogether. Content providers, as we saw
earlier, deal with making the data available for the components. Content providers are
accessed through using a ContentResolver. We will not go into the content providers in this
particular course.

So, in general, intents are an asynchronous message processing mechanism that is used to
activate any of the components, like starting an activity or a service or delivering a broadcast.
So, a broadcast receiver will respond to a specific type a broadcast that comes in based upon
what you intend to use that broadcast receiver for.

As an example, we'll quickly look at the on click method that we implemented in the
GreetFriend application. And here we see a summary of the code that we used on how we
created the intent, how we added the extra information into the intent, and then started the
new activity by supplying the intent as a parameter.

So, in general, reviewing this mechanism, if you need to start a second activity from the first
activity, we will call the StartActivity in the first activity after we create the intent object. Then
this results in a call into the Android framework.

The Android framework, in turn, will respond to this incoming call and then issue a call to start
new activity using that intent by calling the onCreate () method of the new activity.

So, this is the procedure that we use for starting a new activity with an Android. A similar
approach is used when you start a service also. So, intents in Android can be of two kinds. We
have what we call as explicit intents. If we are using an explicit intent, we are explicitly
identifying the component that needs to be started by giving its name.

So, in the example that you just saw, we identified what we want to start, the ShowMessage
activity by specifying ShowMessage.class when we constructed the intent.

There is another way of using intents called as implicit intents. In an implicit intent, we are
specifying to the Android framework saying that we want the Android framework to carry out
this particular action. And we let the framework decide which is the best component to service
that action on our behalf.

So, for example, if we want the Android framework to open a URL location, then we would call
the Android framework as shown in the example down there. We just specify that the action
that we wanted to do the action view. And then supply the URL of the web page to be opened
as the second parameter to this intent object.

Week 2: Introduction to Mobile Application Development Using Android 7


There are many other action items that are available for an implicit intent. This is one example
of such usage. After we complete this quick discussion on intents, we will move to our next
exercise where we'll be extending the GreetFriend example to show a list of friends.

We are going to make use of the ListActivity class in particular and the ListView that is part of
the ListActivity class to display the list of friends. We'll also review the use of adapters where
we take a set of data and then adapt it so that it can be displayed in the list view.

Week 2: Introduction to Mobile Application Development Using Android 8


Week Two: Activity Lifecycle and UI
Lecture 2: Android Activity Intents
Unit 4: Exercise Greet Friend (with ListActivity)

Our final modification to the GreetFriend application introduces the use of a ListActivity within
the application which enables us to display a list of friends. You can then select any of those
friends from the list. And then the application will display the greeting for that friend.

So, to do the modification now, let's go step by step. First and foremost, we will introduce a list
of friends into the strings.xml file as a resource. This approach illustrates the use of resources
and keeping the resources separate from the code.

We can see that when we introduce that resource in the strings.xml file, we can go ahead and
modify the list of friends within this XML file without having to touch the actual Java code. And
the application can display other list of friends if required.

So, to do that, let's introduce a new resource called as a string array resource. And give it a
name as friends. And we'll introduce a list of items here. Each item represents a friend's name.

So, let me introduce four different friends' names. John, Paul, and-- notice how I am leveraging
the suggestions from Android Studio to automatically fill in the code as far as possible. This
minimizes the chances of typing in syntax errors from our side. So, John, Paul, George.

Now you can see where I am going with this. So, these are the names of the four Beatles. Now
once we have completed the string array, then we can use this string array resource and
import it within our code to prepare an array of strings.

Now if you need to modify the list of friends, we can simply come into strings.xml, and then
modify the list of friends here without having to modify the Java code in any way. So, let's save
this change and then move on to the next step.

In the next step, we're going to introduce a new layout file. This layout file specifies how the
items in our list are going to be displayed on the user interface. So, to do so, let's go under
resources and layout subfolder.

And say, New Layout Resource File. And we'll give this file name as friend_item. And then the
root element will be TextView. Let's click OK at this point. And you will see the layout file
coming into existence. At this moment, you can't see anything on the screen. Let's change
some properties of this TextView.

First and foremost, let's give it a default text value. So, go to the Properties. And then, under
text, we will simply type in "Friend Name" just so that we can see where the text is being
displayed on the screen. I want this text to be displayed right in the middle of this layout.

So, to do that, I'm going to go in and change the gravity values. So, go to the gravity property.
And then we would say center_vertical and center_horizontal. So that way, it'll bring this
TextView right into the middle of this whole space here. In addition, let's give it a little bit of
padding around this text so that the display is pretty clear.

Week 2: Introduction to Mobile Application Development Using Android 9


So, for padding, I'm going to say, all the padding will be, say, 20 dp. dp is density independent
pixels. So, this is one way of specifying the space around the TextView. So, we have seen that
for text sizes, we have used sp. And for other properties, we're going to use dp to specify.
So, this way, the specification of the property is independent of the pixel density of the screen.
So, it'll automatically adapt to different screen densities. So, let's give it a padding of 20 dp. And
then we'll save the modifications here. Let's also increase the text size to a slightly larger value.

So, I will give it a text size of 24 sp so that the text is a bit larger to view on the screen. So, with
these changes, let's save the layout file. We will see the use of this in the ListActivity later on, in
code.

The last set of modifications will be introduced in MainActivity.java file. So, let's open
MainActivity.java file and then we will replace this public class, MainActivity. And then we will
extend ListActivity instead of Activity.

So, let's go ahead and modify that to ListActivity. And import that. And you don't need to
implement this View.OnClickListener. So, we can go ahead and delete that part. You will see
that if you are using a ListActivity, you don't need to implement that part. And there will been
some more modifications to the actual code here. Within the onCreate method, let's go in and
make some changes to the code.

The ListActivity comes with its own layout. The layout is a fixed layout which is a ListView.
And it'll display a list of items on the screen. So, we don't need to do the setContentView, so I'm
going to remove that part.

We no longer have this Greet Button, so I'm going to remove that part also. So, we have
cleared out the code from onCreate. And then we will have introduced the new code in the
onCreate method.

I'm going to introduce a new variable here which is a string array with the name names? Within
the code, we will now import the string array from the string resource file that we have already
typed it. So, to do that, we will type in names equal to getResources, getStringArray. And then
we need to supply the ID of that string array.

So, that ID of that string array is R. array. friends. So, we saw that we gave the string array the
name as friends. So now with this construct, we will be constructing an array of strings from
the string array resource that we have already introduced in the strings.xml file.

Now you see how we can keep the code separate from the resources. So, we don't need to
come in and change this code in any way, if we are going to change the list of friends. All that
we need to do is go and edit the strings.xml file, and then introduce a new list of friends there.

After this, we need to specify that this list of names should be displayed in the ListView that is
going to be displayed on the user interface for this application.

So, to do that, we will say, setListAdapter. And we need to supply an ArrayAdapter here as the
parameter for this ListAdapter.

So, to supply the parameter here-- so we'll say new ArrayAdapter. So, this is the standard
ArrayAdapter that is part of what Android supplies. And ArrayAdapter takes a string, and then
converts it into a form that the ListView within Android can make use of when it is constructing
the list of items to be displayed on the screen.

Week 2: Introduction to Mobile Application Development Using Android 10


An ArrayAdapter is of the type string type. And the three parameters for this ArrayAdapter
construction is this, which is this activity as the context.
Then the second parameter is the layout file. So, we would say, R. layout. friend_item. So
basically, we are specifying here that each of those names should be displayed on the screen
using this layout as the method of constructing the layout on the screen. So that's the second
part.

And the third part is the actual array of strings that we are going to supply to this
ArrayAdapter. So, this is names. So, with this, we complete the modification to the onCreate
method of the MainActivity.

Our final modification to MainActivity.java involves the code that will respond when the user
selects one of the items from the list. So, to do that, we need to implement a method called
onListItemClick. So, let me go ahead and then right click there and say, Generate. And we will
say, Override Methods. And then we will select the method called onListItemClick here.

So, this is the method that we need to override to make use of it within the code. So, the
onClick method is no longer needed. So, I'm going to delete this part of the onClick method.
This is no longer needed here.

Now you will also notice that the code will now get simplified because the name of the friend
will be automatically retrieved from the name's array that we have used to construct the
ListView.

So, I'm going to delete all this code. This is no longer needed for me. And similarly, I will delete
the rest of the code at the bottom. That is no longer needed. But this part of the code, I will be
needing inside my list item click method. So, I'm going to shift all this code into my list item,
and then make some modification to that. So, let me go ahead and then cut and paste it into
my ListView.

So, when this onListItemClick method is called, it is receiving four parameters here. It says,
ListView l, View v, int position, and long ID here. So, from these, we will be able to identify
which particular item in the list has been clicked.

In particular, the value-- the long ID specifies which of the items in the list was clicked. So, if
you have a list of 10 items, and then you selected the fifth item in the list so the long ID will
return the fact that you selected the fifth item in the list.

So, we're going to make use of that in order to construct our message to be sent to the
ShowMessage activity.

So, within the code, we will come in here and then, instead of the friend name, I am going to
replace the friend name with names and the position being the ID here. And then because ID is
long, I have to cast it to integer value so that it can be properly used within the code. And then
save the changes here.

Finally, when the app is deployed to the emulator and starts running, you will see this screen.
Here, we have the list of friends being displayed. So, if you click on any one of those friends,
then the message corresponding to the friend will be displayed on the screen.

Week 2: Introduction to Mobile Application Development Using Android 11


So, you can always go back and click and select another friend. And so that is how the ListView
enables you to display a list of friends and select one of them. And it displays the message
corresponding to that friend.

Week 2: Introduction to Mobile Application Development Using Android 12


Week Two: Activity Lifecycle and UI
Lecture 2: Android Activity Intents
Unit 7: Exercise Greet Friend (with Lifecycle)

In this exercise, we'll start with the GreetFriend with list view and then modify it in order to
understand the life cycle methods of an Android activity.

So, to do that, let's go into MainActivity.java and then add in a variable here saying private static
final TAG. And we will use this tag later on to output some long messages on the screen. So,
we'll see how those long messages work in practice.

So, with the tag added there, let me go ahead and the add in a log message, say Log.i(TAG, And
I'll say-- so using log messages, we are able to type out things into the log window so that we
can track the progress of our application as it is executing on the device.

So, let's add in this to the onCreate () method. Similarly, we will soon learn that an Android
activity has several other lifecycle methods. In particular, let me add in a few more lifecycle
methods for the Android activity.

So, we'll say generate and override methods. So, we'll add in-- for the activity we'll say onStart ()
onRestart () onResume (). Then onPause (), onStop (). And the last one I need is the onDestroy ()
method. So, let me see where it is.

Let's go ahead and add these methods first. And then I will also add in-- again, I try as far as
possible to take the help of Android Studio to fill in as much of the code as possible so that it
will avoid me having-- typing in errors. So, we have several different methods here onStart (),
onRestart (), onResume (), onpause (), onStop (), and onDestroy () methods.

Later on, I will explain to you what these methods are and how they play a role in the lifecycle of
an Android activity. For the moment, let's take this log message and then we will just log the fact
that each of these methods are being executed by an Android application as it is executing. So, I
will have this long message being printed by every one of these lifecycle methods.

So, for the onStart () I would say onStart. And so on. So, let's add in for each one of those
methods. So, once you have completed adding in the log statement to each one of these
methods, let's copy all these methods and also add them to the show message activity.

So, I'll just type in here. And for the show message activity also I will add in the tag variable.
ShowMessage. Now once we have completed this-- oh. In addition, I should also type in for the
onCreate () method here. So, let's go ahead and save.

Let me quickly explain how these lifecycle methods work in practice. We will examine it in more
detail later on. First and foremost, we already learned that when the Android framework starts
your activity, it is going to call your onCreate () method.

After calling the onCreate () method, the framework is going to come in and call the onStart ()
and the onResume () method in quick succession. And your activity then occupies the screen,
and its UI will be displayed on the screen. When the activity disappears from the screen, then
the Android framework will call the onPause () and the onStop () method.

Week 2: Introduction to Mobile Application Development Using Android 13


Now the reason why an activity may disappear from the screen is because either you hit the
back button or you hit the home button for an activity. Now if one activity is switching to
another activity by starting a second activity, then their life cycle methods of the two activities
will intermingle with each other in the way they are called.

So, we will examine this in a bit more detail when I explain the theoretical aspect of this after
we complete this exercise. So, once you have updated the MainActivity and ShowMessage.java
file, let's go ahead and run this application and then observe what happens in the log window
on the screen.

Now that your GreetFriend application's main activity's UI is displayed on the screen, it is
interesting to note that for the main activity the onCreate (), the onStart (), and the onResume ()
methods will be called in quick succession one after another. So, this is the logcat window
where the log messages are printed outas your application is running on the screen.

Now let's go ahead and click one of these list items. So, when you click that list item, you will
immediately notice that the onPause () method for the main activity was called. And then,
subsequently, the onCreate () method for the show message activity was called. And then the
onStop () method for the activity was called thereafter. And now you see the show message
activity being displayed on the screen.

So, this completes our examination of the lifecycle methods of Android. Now in this example,
we have not actually seen the real use of these lifecycle methods. In one of the later exercises,
we will employ these lifecycle methods to actually control some aspects of your app behavior.

Week 2: Introduction to Mobile Application Development Using Android 14


Week Two: Activity Lifecycle and UI
Lecture 3: Activity Lifecycle
Unit 1: Activity Lifecycle

We have just seen the greet friend example, which illustrates the use of an activity's lifecycle
methods. Let's examine these lifecycle methods in a little more detail now. So, what we have
realized is that every component in Android has a lifecycle. This lifecycle starts when the
component is created, so from the beginning, when the Android framework initiates the
component, and until the component is destroyed.

So, in between these two points, your component goes through its lifecycle evolution. As your
component is going through its life cycle, sometimes it may be active, and sometimes it may be
inactive. Now depending on, for example, if an activity is currently occupying the screen, then
the activity is active at this moment. But when an activity is no longer visible on the screen,
then it becomes inactive.

So, depending on the circumstances, your components may be in one of several states. Let's
look at the activity itself in a little more detail. An activity could be in one of 3 states, either
resumed state, paused, or stopped state. In the resumed state, as you would expect, the
activity's occupying the screen. And its user interface is being displayed on the screen.

When the activity's in the paused state, then the activity is no longer the recipient of the user's
interactions on the screen. And so, although it may be still visible, but the user cannot interact
with that activity. An example of a situation like this is when an activity is covered by a dialog
box in Android when it pops up.

So, you can still see that the activity is visible on the screen. But you cannot interact with it
directly. The stopped state, obviously, is a situation where the activity is no longer visible on
the screen. So, it is still in existence. But it is in the background and not occupying the screen at
the moment. If an activity is in the stopped state and your Android device is running out of
memory, then the framework may come in and kill your activity, or it may ask the activity to
finish by calling the finish method of that activity.

We will see how this all plays out when we look at the evolution of an activity through its
lifecycle. So, examining the activity's lifecycle in a bit more detail-- now, every activity in
Android has certain lifecycle methods associated with it. We have already seen the onCreate ()
method of the activity. We saw that, to create the activity, your Android framework needs to
call the onCreate () method.

There are other methods that are part of that activity lifecycle, like that onStart (), onResume (),
onPause (), onStop (), onRestart (), onDestroy (). Let's see how these methods come into play as
your activity evolves through its lifecycle.

First and foremost, when your Android framework needs to create the activity, it is going to
invoke the onCreate () method of your activity. So, it'll call the onCreate () method. That's the
reason why we implement the onCreate () method inside our activity class. Now, if you do not
explicitly implement a method, then the default method of the superclass is going to be used
in its place.

Week 2: Introduction to Mobile Application Development Using Android 15


However, onCreate () method is a special method. You have to implement that in your activity.
The remaining methods are optional for your activity. So, once the onCreate () method is
invoked, then your activity moves into the created state. So, your activity has come into
existence. But it is not currently active on the screen.

Now, once the onCreate () method is executed, then the Android framework will come back
and call the onStart () method of your activity. Upon completion of the onStart () method, then
your activity moves into the started state. The activity starts beginning to be visible, but not yet
occupying the screen completely. After the onStart () method is called, the Android framework
is going to come and call the onResume () method that you implemented within your activity
class.

The onResume () method will cause your activity to come up and occupy the screen. So, at this
point, your activity moves into the resumed state and now becomes visible on the screen. So,
to the right side, you'll see that the greet friend activity, if that is taken as an example, now
comes up onto the screen and becomes visible on the screen.

Now, if you hit the back button, for example, then the Android framework realizes that you
need to remove the activity from the screen and then go back to the launcher screen. So, to do
that. Your Android framework will call the onPause () method of your activity. When the
onPause () method is called, your activity then moves into the paused state.

So for example, if you pop up a dialog box on the screen, your activity then moves into the
paused state, because the framework calls your onPause () method. And then the dialog box
comes up onto the screen. So, in that case, your activity is still visible. But you cannot directly
interact with it.

Subsequently, if the Android framework calls the onStop () method, at this point, this is an
indication that your activity should go from the screen, should release the screen and then go
into the background.

So our state upon completion of the onStop () method, your activity will go into the stopped
state. And then it is hidden from the view. So, such calls to the lifecycle methods of your
activity causes change to the state of your activity as it evolves through its lifecycle.

So this is one example of an interaction between the framework and your activity that causes
your activity to move into different states. So in general, an activity's lifecycle evolves as per the
diagram presented here. So when you first launch an activity, then the Android framework is
going to call the onCreate () method, subsequently call the onStart () and onResume () method.

Upon completion of the onResume () method, your activity will come into the running state. So
at this state, your activity is occupying the screen. If you then have a reason for the Android
framework calling your onPause () method-- so for example if, from within your activity, you
invoked another activity,

so in the example that you saw, when you clicked the button on the main activity that caused
the show message activity to be started-- so in that case, Android framework is going to come
and call the onPause() method of your activity, and then subsequently call the onStop() method
or your activity. At this point, your activity has stopped.

Week 2: Introduction to Mobile Application Development Using Android 16


Now, if your activity is in the onStop() method, and then, say you return to the activity either by
clicking a back button or by reselecting that activity to come up on the screen, then the
Android framework will call the onRestart() method, and then return and call the onStart()
method and onResume() method. And then your activity will come back to the running state.

So, from the show message activity, if you hit the back button and then come back to the main
activity, this is the sequence that is going to take place. The onRestart () method is going to be
called. Then the onStart () method is going to be called And then the onResume () method is
going to be called. And thereafter, your main activity will come back onto the screen.

Suppose you hit the back button at this point. Then you are exiting from the main activity. And
you're exiting from the application, also. At this point, then your onPause () and onStop () are
going to be called in sequence. Then the onDestroy () method is going to be called. This
indicates that your activity is going to be shut down at this point and is no longer active. So it
completes the lifecycle of your activity.

If your activity is in a paused state or the stopped state, and if the device is running out of
memory, then the Android framework may come in and kill your activity. And so that's the
interactions that you see to the left side of this diagram, so the app process being killed. But
subsequently, if you return to your application, then Android framework promises that it will
recreate your application.

So this process is initiated by, again, calling the onCreate (), onStart (), and onResume ()
methods-- in that sequence-- to restore your activity back to the user interface. Now, let's ask
ourselves, under what circumstances is your activity active? So between the call to the
onCreate () and the call completion of the onDestroy () is your entire lifetime of your activity.

Once the onDestroy () method is called and it completes execution, your activity is no longer
valid. So this is what I refer to as the entire lifetime of your activity. Now, between the
completion of the onStart () method and just before you invoke the onStop () method is what I
refer to as the visible lifetime. So, in this case, your activity is visible on the screen.

You may not be able to interact with it under some circumstances. But it is still visible on the
screen. Then finally, I defined the time between the completion of the onResume () method
and the invocation of the onPause () method to be the foreground lifetime. In the foreground
lifetime, your activity is actually occupying the screen. And so, it is visible on the screen at this
point. So, this is the entire activity lifecycle in a nutshell for you to understand.

Now, how are you going to make use of these methods? In many of the applications that you
implement, you may not even have to implement any of these methods, other than the
onCreate () method. But in some circumstances, as we will see in an example later, you will
take advantage of the presence of these methods and appropriately execute code that should
be executed when your activity in a certain state and moving on to the next state.

So, for example, if you are playing music while your activity is occupying the screen, then you
would resume playing of the music in the onResume () method. But when your activity is no
longer on the screen, and if you want to pause the music, you will pause the music in the
onPause () method of your activity.

We will actually see this being used in one of the examples later on in this course. So, this
completes a quick discussion about the activity lifecycle. Let's now ask ourselves, if one activity

Week 2: Introduction to Mobile Application Development Using Android 17


invokes a second activity, then what really happens? What is the order in which these methods
are going to be called? As we saw in the greet friend example, the main activity was invoking
the show message activity in order to display the message on the screen.

So, in those circumstances, the main activity was first occupying the screen. And when you hit--
when you clicked the greetings button, at that point your Android framework has to pause
your main activity. But then it can't stop your main activity at that point because something
else has to come up to occupy the screen at that point.

So that's why Android framework will first invoke the onPause () method of your main activity.
At that point, it'll then have to create the show message activity. So, it is going to call the
onCreate (), the onStart (), and the onResume () method of the show message activity. And
then the show message activity shows up on the screen and is occupying the screen. At that
point, it is safe to stop the main activity. So, at that point, the onStop () method of your main
activity is going to be called.

So, if you have switching between activity A and activity B-- so the steps of invoking these
methods is first, A's onPause () method is going to be called. Then B's onCreate (), onStart (),
and onResume () method is going to be called, in that sequence. And then, when B occupies
the screen, then A's onStop () method is going to be called to stop activity A at that point.

So, this is what I refer to as the lifecycle dance between the two activities as they go through
their individual lifecycles. So, this completes our entire discussion on activity lifecycle. There’s
more to it than what I have explained here. But we will learn as we go along in the course. So,
let's move on to our next application where we're going to implement the user interface for a
chat client.

So, this is somewhat of a meaningful example to illustrate to your certain aspects of the
Android UI design and also some other features of the Android platform. So, we'll look at
ListViews. And then we'll look at how we create custom adapters for our application. And we
also examine some additional layouts, like the linear layout, for creating the user interface.

Week 2: Introduction to Mobile Application Development Using Android 18


Week Two: Activity Lifecycle and UI
Lecture 4: Chat Client App Overview
Unit 1: Chat Client App Overview

Our next set of exercises and assignment concentrateson developing a user interface for a
chat client. In the set of exercises, we will have explored the use of further Android UI widgets
like ListView and also look at using layouts.

In addition, as the final step, we will look at the use of material design aspects in our user
interface. As a first step in this exercise, we will develop a simple chat client application. This
application will allow the user to input a message, and when the send button is clicked, the
message will be added to the list of messages in the user interface.

So, for example, we can type in a message. And then when you hit the send button, the
message is added to the list of messages here. This exercise takes the help of a ListView for
showing the messages and also uses a LinearLayout in closing in any text field and a send
button that enables the users to type in their messages.

In the second step, as part of an assignment, you will modify the simple chat client into a full-
fledged chat client which will display both incoming messages as well as the messages you
type on the screen. So, for example, this is simulated interaction with a distant user who is
communicating with you using this chat client.

So, for example, if you type in hi and then you would see an incoming message coming in from
the other user. And so, you can continue on with the conversation, as you see. So here you can
clearly see both the incoming messages as well as the messages you type to send to the other
user on the screen.

This exercise takes the help of the ListView. But here, we are using a custom adapter for the
ListView whereby you're able to display the two messages in two separate ways. You have the
incoming message on the left side and the outgoing message on the right side oriented
towards the right side of the screen.

In other final modification of the chat client application, we add in a feature that enables you
to display a list of contacts. And then you can select one of those contacts and then start
messaging with that particular friend. So, this takes the help of two activities-- one being the
contacts activity and the second one being the chat client activity.

So, when you select one of the friends, then the chat client activity will open on the screen and
then enable you to communicate with your friend. And so on. So, in the simulated
conversation, we are showing the features of the user interface for the chat client application.
Now, this modification to the chat client application takes advantage of first and foremost the
material design that is part of the new Android platform.

We have developed this application to the backward compatibleup to the API 18 by using the
compatibility libraries. In addition, we are using the RecyclerView for displaying the messages.
We are using the styling that is available in material design to put in various colors for the user
interface and also use an image button on the screen in place of the send button.

Week 2: Introduction to Mobile Application Development Using Android 19


Week Two: Activity Lifecycle and UI
Lecture 4: Chat Client App Overview
Unit 3: Exercise Chat Client App

We'll build up the Chat Client application in stages. In the first step, we'll build a simple Chat
Client, which takes the user's message and then displays it on the screen. To get started,
download the zip file that we have provided to you, and then import the project into Android
Studio. Once you have imported the project, you will notice that we have pre-configured
certain parts of the project already for you.

This is so that we can concentrate on those aspects of this app that are relevant to the
knowledge that we are trying to get at this stage. After you import the project, let's go ahead
and examine those parts that have already been completed, and then we will look at those
parts that we need to complete. Go ahead and then open, first and foremost, the
activity_chat_client.xml file. This is the layout of the user interface for our Chat Client So in this
layout, you will notice that there are three parts to the user interface.

First and foremost, you have a ListView that displays a list of messages, then we have an
EditText box, which allows the user to enter their message. And then we have a Send button,
which the user clicks in order to send the message.

Now within the code, the way this user interface is designed is that the EditText box and the
Send button are enclosed inside a linear layout, which is a horizontal linear layout so that
these two items can be positioned side by side on the UI. Now the third part, the ListView is
enclose in another linear layout, which is separate from the first one, and then positioned on
top of the linear layout down here.

These two are then enclosed inside a relative layout so that they can be positioned on the
screen appropriately. Now to understand it better, let's switch to the TextView of this layout.
You will notice that there is the overall view group, which is a relative layout out there. And
then we have two linear layouts inside this overall group, and then one of the linear layouts
includes the EditText field and the button. And the second linear layout encloses just the
ListView.

And using the positioning features available within the layout we have positioned the linear
layout with the Text field and the button at the bottom of the screen so you notice that I have
aligned it to the parent bottom, and then left and the right of the parent.

So, this way, this linear is positioned right at the bottom of the screen. Now the second linear
layout, I have positioned it to be on top of the first linear layout. So that's why I say layout
about, and then specify the ID of the first linear layout.

So, using relative layout, you can position different items on the screen by specifying their
relative positions on the user interface. So, spend some time looking at this code and also the
design view of this layout so that you understand how to design a bit more complex layout for
applications.

Week 2: Introduction to Mobile Application Development Using Android 20


In addition to this, we see that since we have a ListView here, we need to design the layout for
each one of those list items. This is available to you in the second layout file that we have
provided for you called as message.XML.

This message.XML file is again a layout with two TextViews, one for displaying the message,
second for displaying the time. And both of these are enclosed inside a linear layout, which is a
vertical linear layout.

So, these two are positioned one below the vertical linear layoutwith the message being
positioned to the left side and the time value being positioned to the right side inside the linear
layout. This linear layout is then enclosed inside a relative layout which displays the whole
message as a unit.

So, switching again to the TextView, you will notice that we have a relative layout surrounding
the linear layout. And inside the linear layout we have two TextViews. Spend a little bit of time
looking at how we have positioned these two items inside the layout file here in order to
achieve the UI design as seen in this layout here.

OK, after we finish looking at the two layout files, let's spend a little bit of time looking at the
third part which has been completed for you. This is the message class that I have included.
The message class is used to create message objects.

The message class contains all the fields that enables you to store pieces of information
related to a single message.

So when you go in, you will notice that I have several variables here which store the message
there from name, meaning who the message is from, the name of the sender in Boolean field,
which stores whether this message is from me or from another sender and also another field
called as a date field where I store the timestamp for this message.

All these are included inside here, and then you'll also notice that I have setter and getter
methods for each one of these fields that are included here.

Again, once you're familiar with Java, you will immediately understand why I have cleared all
these different setter and getter methods for this message class. Now this message class is
used to construct the various message objects that are going to store each single message for
display on the screen.

Now finally, we have two other Java files that are part of this project. One is ChatClient.java,
which I will examine in a little more detail. The second one is, again, the Java class called as
MyArrayAdapter.

This MyArrayAdapter is an extension to the ArrayAdapter that we have used for the ListView in
the previous example. I have extended this ArrayAdapter because later on when I need to
display messages from two different users on the screen,

I need the flexibility that the custom adapter provides for me to construct the layouts of the
messages on the screen. Now this also enables us to understand how a typical ArrayAdapter
works in practice.

Week 2: Introduction to Mobile Application Development Using Android 21


As I mentioned in the previous exercise, ArrayAdapters enable us to take the data and then
construct views from the data. So, we will see the construction of the message view from the
message object inside this ArrayAdapter, so we need to fill in some part of the code.

So I have set up parts of this class already for you to get you started quickly. We'll fill in some
part of the code in order to construct the view.

Finally, we have the Chat Client activity that we define in Chat Client or Java file. This is a
standard activity description. This is what drives the entire application. So, you will see that we
have the onClick listener for the Send button here.

We have a reference to the EditText field here and so on. So now we need to fill in some part of
the code to be able to retrieve the message that the user types in and then display the
message on the screen, so those parts we will fill in as we go through this exercise.

Let us now go ahead and then edit the MyArrayAdapter class to be able to construct the view
from the message object. So, to do that, we'll go into the getView method here. And then add
in the appropriate code here.

So first and foremost, let's create a variable called as MessageView, then we get access to the
Layoutinflater that is available in Android. To get access to the Layoutinflater in order to
construct the view, we will say layout inflater and get access to the Layoutinflater inflater.

So, we will say Layoutinflater and say context and getSystemService context and then
LAYOUT_INFLATER_SERVICE. So, once we get access to the inflater, we can then go ahead and
construct our view using this inflater.

Once we get hold of the inflater, let's now go ahead and inflate the MessageView from the
message.XML file. So, to do that we'll say MessageView inflater inflate. And we'll say R. layout.
message, so we are constructing this MessageView by using the message layout.

The second one is the ViewGroup within which it resides, which is the parent, and finally, we'll
say false. So, this statement enables us to inflate the MessageView.

Now we would like to initialize the various TextViews inside this message for you. So, let's go
ahead and get references to these TextViews, and then set the values of these TextViews.

From this MessageView, we will not get the references to the TextViews that are part of the
messageView so let's say TextVew, say messageView, and then we'll say messageView
findViewByID and r.id. And then we'll get the message TextView.

That's one of the TextViews that we need, and so we should see TextView. And then we're
going to set this messageView to the message strict, so we'll say messageView set text, and
we'll say messages get the position.

So, we are trying to find the message at that particular position for which we are currently
inflating the view, and then we'll say and then getMessage.

So now we have initialized the message string there. The second part that we need to initialize
is the time value, so we'll say TimeView is TextView. Now again, messageView and then
findViewById. And r.Id. we'll have the time TextView there, and then we'll say TimeView, and
then setText.

Week 2: Introduction to Mobile Application Development Using Android 22


And then for that particular message, we'll say getTime, and then we'll set the time value
appropriately. Now once we have initiallized the two, TextViews and the MessageView. we can
now go ahead and then return this MessageView from this method. So, we'll say Return
messageView, and so we have completed the update of the code for the ArrayAdapter.

So, when your UI is constructing the list view, it is going to call into this getView method and
then be able to construct one item at a time off the ListView. So, let's go ahead and save this
change, and now we will go and edit the Chat Client or Java 5 to complete this exercise.

Let's now proceed to complete the code inside Chat Client or Java 5. So, in here, we see that
the first place that we need to fill in the code is in the onCreate method. So here, first and
foremost, let me get a reference to the ListView. So, we'll say MessageList, ListView, which is
part of the UI, so findViewById MessageList.

So now we have the access to the ListView, so I'm next going to create the ArrayList of type
message, so I will say new ArrayList of type message. OK, so now that we have messages, then
we are going to use this messages ArrayList to construct the adapter in order to initialize the
ListView.

So, from the messages, we need to construct the ArrayAdapter, so I would say m adapter new
MyArrayAdapter. We have seen that we have already created the MyArrayAdapter. I'll supply
the context, and then I will supply the messages as the second parameter.

OK, so this helps me to construct the ArrayAdapter. Now I'm going to take this adapter and
then use that to initialize the ListView. So, I will say MessageList set adapter. I will then say
ListAdapter and then cast the m adapter as the ListAdapter. So, with this, I complete the
modification to the onCreate method. So here, the four statements that I added.

First, I got a reference to the ListView, then I created the messages ArrayList, then I created an
adapter from the message ArrayList using the MyArrayAdapter class that I implemented
earlier. Then finally, I initialize the adapter for my ListView to be equal to the adapter that I just
created.

So, let me go ahead and save these changes. We will now go to the last part and then update
onClick method so that when the user types in the message end clicks the Send button, we'll
be able to retrieve the message and add the message to the ArrayList of messages.

Coming down to the onClick, we will now edit the code here to add in an appropriate set of
codes to handle when the user clicks the Send button. So, when the user clicks the Send
button, I have now retrieved the message from the EditText field.

Now we need to create a new message object and then initialize the message object and then
add this message object to the messages ArrayList. Let me go ahead and create a new
message object and then initialize it with the appropriate values.

So, I will say message, new message and the first parameter is the name of the sender. So,
since this message is created by the user himself or herself, so the first parameter is set to
blank.

Week 2: Introduction to Mobile Application Development Using Android 23


The second parameter is the actual message, so that'll be set to the messString.The third
parameter indicates whether thismessages is from the useror from the other person with
whom you're communicating. Since this message has been created by the user, we'll set the
value to true.

And then finally the last parameter sets the date value so the time stamp. So, I will say new
date. So, this completes the initialization of the new message object.

Now once I created the message object, let me go ahead and add this message object to
messages. So, I will say message, messages, addMessage. And once I have added the message
object, the third thing that I need to do is to indicate to the adapter that a new message has
been added, so the user interface needs to be updated.

So, to do that I will say m adapter notifyDataSetChanged. So, calling this method called
notifyDataSetChanged causes the ListView to read in the updated adapter and then refresh
the ListView so that the new message now becomes part of the screen.

Finally, I will release the message. Object, it is no longer needed, and then also I will set the
message text to blank. So, with this, the modification to the onClick method is complete.

With these changes, let's go ahead and then run this application and see how it works on the
screen. Once your application is deployed to the emulator and starts running this is what you
will see on the user interface of the emulator.

Or if you're using a real device, this is what you'll see on the real device. So, let's go ahead and
type in a message. So, we'll say test, and when you click on the Send button, you should see
the message being displayed on the screen. So, let's add one more, and you will see now how
the simple Chat Client is able to keep adding messages.

So now we have a fully functional simple Chat Client example, so it is able to display a message
on the screen. In addition, it is able to show the time at which this message was input by the
user, so now we see the fully functional simple Chat Client, which is able to display the
messages on the screen including the time at which the message was input.

This completes this part of the exercise. Now we'll more on to doing the assignment

Week 2: Introduction to Mobile Application Development Using Android 24


Week Two: Activity Lifecycle and UI
Assignment: Edit Client Chat App
Unit 1: Edit Client Chat App

In this assignment, you will be modifying the ChatClient application so that it displays both
incoming and outgoing messages in two different formats.

So, for example, if I type in a message and click on the Send button, the message that I send
out will be displayed towards the right side of the screen, whereas an incoming message from
the other party that I am communicating with will be displayed to the left side of the screen.
So, as you can realize, this involves using two different layouts for both outgoing messages and
for incoming messages.

Now, we have provided you with a pre-configured project which contains the layouts pre-
defined for you. You need to go in and fill in part of the code to enable the display of the two
messages on either side.

Once you download and import the project into Android Studio, you will notice that we have
already filled in the code for the ChatClient application to simulate bi-directional
communication. You don't need to modify anything in the ChatClient application. Much of it is
very similar to what you have seen with the previous exercise.

In addition, we have added two layouts here, the message.xml, which you have already seen
being used in the simple ChatClient application, and we have added a layout called
mymessage.xml, which is what you're going to use to display outgoing messages to the right
side of the screen.

So, this involves going in and modifying the MyArrayAdapter.java file, such that depending on
whether it's an outgoing or an incoming message, your display of the message in the list view
will be different.

So, we have put in the skeleton code here, and then identified the locations where you need to
fill in the code in order to simulate the new behavior, or the layout of the two kinds of
messages on the screen.

Week 2: Introduction to Mobile Application Development Using Android 25

Вам также может понравиться