Programming Question

Hello, I want help with my homework, please check attached

Save Time On Research and Writing
Hire a Pro to Write You a 100% Plagiarism-Free Paper.
Get My Paper

Important: I need you to answer on the (same) doc file I attached please, don’t do it on a different file/doc, I need the answer to be on the same one I attached please.

College of Computing and Informatics
Assignment 1
Deadline: Day 1/10/2023 @ 23:59
[Total Mark for this Assignment is 8]
Student Details:
Name: ###
ID: ###
CRN: ###
Instructions:
• You must submit two separate copies (one Word file and one PDF file) using the Assignment Template on
Blackboard via the allocated folder. These files must not be in compressed format.
• It is your responsibility to check and make sure that you have uploaded both the correct files.
• Zero mark will be given if you try to bypass the SafeAssign (e.g. misspell words, remove spaces between
words, hide characters, use different character sets, convert text into image or languages other than English
or any kind of manipulation).
• Email submission will not be accepted.
• You are advised to make your work clear and well-presented. This includes filling your information on the cover
page.
• You must use this template, failing which will result in zero mark.
• You MUST show all your work, and text must not be converted into an image, unless specified otherwise by
the question.
• Late submission will result in ZERO mark.
• The work should be your own, copying from students or other resources will result in ZERO mark.
• Use Times New Roman font for all your answers.
Question One
Pg. 01
Learning
Outcome(s):
Question One
Design
Based on the below image displayed as XML file, answer the following
questions.
1 Mark
application
interfaces for
mobile devices
1. What is the type of the used layout and explain it?
2. How many child elements are there for this layout and name it/them?
using appropriate
software.
Answer:
Question Two
Pg. 02
Learning
Outcome(s):
Describe
technologies that
enable the
development of
applications for
mobile devices.
Question Two
2 Marks
Explain the two different classes from the Android API that allow us to output
messages. Give an example for each message by adding your name and
student ID.
Answer:
Question Three
Pg. 03
Learning
Outcome(s):
Design
application
interfaces for
mobile devices
using appropriate
software.
Question Three
3 Marks
Write XML file for the following project’s screenshot. The project has one activity
and displays the following:
1. The activity shows a login page with TWO TextView and TWO EditText and
TWO Buttons.
2. Choose the appropriate Layout.
HINT: Include the screenshot of the layout’s output, after you run the app, as
a part of your answer. Also, upload your project’s file. Otherwise, you will be
marked zero for this question.
Answer:
Question Four
Pg. 04
Learning
Outcome(s):
Design
application
interfaces for
mobile devices
using appropriate
software.
Question Four
2 Marks
Write One XML code to show a photo gallery using the ScrollView element.
1. Use TableLayout to arrange photos.
2. Use ImageView and TextView elements.
The following screenshots are an example of the required app. Write an XML
file to design the app as stated above. You will need to use both ScrollView
and TableLayout structures to build the app.
HINT: Include the screenshot of the layout’s output, after you run the app, as
a part of your answer. Also, upload your project’s file. Otherwise, you will be
marked zero for this question. In addition, you can google the flower images
from the Internet to use them in your application.
Question Four
Pg. 05
Answer:
College of Computing and Informatics
Bachelor of Science in Computer Science
IT448
Mobile Application Development
Week 2
Beginning Android and Java &
First Contact Java, XML, and the UI designer
Contents
1. Why Java and Android?
2. How Java and Android work together?
3. Understanding the Android API
4. Setting up Android Studio
5. Building our first Android app
6. Exploring the project Java and the main layout XML
7. Examining the app layout file
8. Adding buttons to the main layout file
9. Coding messages to the user and the developer
Weekly Learning Outcomes
1. Explain the basic concept of Android & Java.
2. Demonstrate the steps is needed to setup Android Studio.
3. Explain how to build first Android app.
Required Reading
1. Chapter 1 and Chapter 23 (Android Programming for
Beginners 3rd Edition, 2021 by John Horton , Packt
Publishing Ltd.)
Why Java and Android?
Why Java and Android?
• Java the popular programming language is used to develop Android
applications.
• Java has an extensive set of libraries. It is easy to take advantage of these
libraries. has many standard Java libraries included. These provide
functionalities Android SDK for data structure, math functions, graphics
implantation, and networking functions and much more.
• Java help in creating, improving android applications with many libraries
and tools of java make Android application developing easier.
• Java helps develop Android applications fast and in efficient manner.
• Android easily implement and fix common problems with other
programming languages with the help of Java.
How Java and Android work together?
How Java and Android work together- ART system
• JAVA code for android is converted into bytecode after compilation.
• This bytecode is then converted into machine code by Android Runtime
(ART) when the application is installed by users.
• *Java is fast for the programmer to program→ conversion to machine code
is fast for the device by ART.
• ART system: provides hooks into application and
• Enhance memory management while the application is running -> app
run more efficiently.
Understanding the Android API
Understanding the Android API
• Android API (Application Programming Interface) → Collection of Java code that
has already been written to use it as plug and play.
• Android framework API → use by applications to interact with the underlying Android
system.
• *Java programming language → enable to handle programmer’s complexity.
• An API is a software intermediary that allows two applications to talk to each other.
• *API is the messenger that delivers the request to the provider delivers the
response back.
• APIs enable developers → to create complex processes highly reusable with a little
bit of code.
• APIs play a vital role in helping developers build out apps faster and more
efficiently.
Java is object-oriented
• Java is an object-oriented language uses the concept of reusable
programming objects
• Java enables to write java code that can be structured based on real-world
things.
• Class is the blueprint/design of an object in object-oriented programming
(OOP) concept.
• When a class is transformed into a real working “thing,” it is termed as an
object or an instance of the class.
What exactly is Android?
• *Android programming uses JAVA code: compiled bytecode and
translated into machine code by ART when installed.
• Android is Linux based operating system → handles the complex and
extremely diverse range of hardware of variety of android devices.
• Advanced software called drivers provided by the device manufacturers
ensure that the hardware (CPU, GPU, GPS receivers, memory chips,
hardware interfaces, and so on) can run on the underlying linux operating
system.
• Android Application Package (APK) → bundle of files that consists of
bytecode + supporting resources.
• *ART uses this bundle to execute and prepare app for the user.
Setting up Android Studio
Android Studio
• Official Integrated Development Environment (IDE) for android app
development environment.
• Two major components:
 JDK: To use/write Java code
 Android SDK: Collection of tools for Android development and Android
APIs.
• Tasks by Android Studio
 Provides an IDE
 Compiling code
 Linking with the JDK and the Android API
Setting up Android Studio
1. Download Android Studio from https://developer.android.com/studio
2. Create a new folder on the root of C or D drive called Android. Inside the
Android folder, create another new folder called Android Studio.
3. Navigate back to the Android folder and create another new folder named
Projects, to keep all the project files.
4. Create another new folder called SDK, to installer program to install the
Android SDK. Should now have a D:\Android folder that looks like this:
Setting up Android Studio
5. Once the download is complete, find the downloaded file.
6. Double-left-click the file to run it.
7. Enable the administrative privileges and begin the installation. On the Choose
Components screen, make sure that both the Android Studio and Android Virtual
Device options are checked, and then left-click the Next button:
Setting up Android Studio
8. On the Configuration Settings window, left-click the Browse button and
navigate to D:\Android\Android Studio, and then left-click the OK button:
Setting up Android Studio
9. Left-click the Next button shown in the preceding screenshot. On the Choose
Start Menu Folder window, left-click Install to accept the default option. The first
part of the installation will now proceed.
10. Once getting the Installation Complete message, left-click the Next button, then
left-click the Finish button.
11. *It will be prompted that a missing SDK (unless this is not the first time is used
Android Studio). Left-click Next to continue.
12. *On the SDK Components Setup screen shown next, change the install location.
Left-click the Android SDK Location field and browse to D:\Android\SDK, as
shown in the following screenshot:
13. SDK Components Setup screen Left-click the Next button.
14. On the Verify Settings window, left-click the Finish button. Android Studio
will now download some more files and complete the installation. It could
take a few minutes or more and will prompt to allow access to the PC.
15. When the process is over, left-click the Finish button.
Building our first Android app
Building our first Android app
• Steps to start the project:
1. Run Android Studio. On
Windows 10, for example,
the launch icon appears in
the start menu.
2. Android Studio
welcome screen, as
shown in the following
screenshot.
3. Locate the start a new
Android Studio project
option and left-click it:
5. The window that follows is Select a Project Template.
6. Select Basic Activity. Here is a picture of the Select a Project Template
window with the Basic Activity option selected:
7. Ensure Basic Activity is selected as it is
in the preceding screenshot, and then click
Next.
8. After this, Android Studio will bring up the
Configure Your Project window: Enter the
details of the project here:
a. Name the new project.
b. Choose the location on the system to
save the project files.
c. Provide a package name to distinguish
our project from any others in case we
should ever decide to publish the app
on the Play Store.
d. Select the programming language we
will use.
8. The next screenshot shows the Configure
Your Project screen once you have entered
all the information:
Exploring the project Java and the main layout XML
Exploring the project Java and the main layout XML
• Examining the MainActivity.java file
• Java code can be viewed by left-clicking on the MainActivity.java tab, as
shown in the figure below:
Figure 2.2 – MainActivity.java tab
Only an annotated screenshot is required than reproducing the actual code in
text form.
Figure 2.3 – Java code
The package declaration
• Part 1 is called the package declaration and, it is the package name we chose
when we created the project preceded by the word package. Every Java file will
have a package declaration at the top.
Importing classes
• Part 2 is eight lines or more of code that all begin with the word import. After the
word import, there are various dot-separated words. The last word of each line is
the name of the class that line imports into the project and all the earlier words in
each line are the packages and sub-packages that contain these classes.
• *For example, this next line imports the AppCompatActivity class from the
androidx.appcompat.app package and sub-packages:
import androidx.appcompat.app.AppCompatActivity;
The class
• Part 3 of our code is called the class declaration.
• public class MainActivity extends AppCompatActivity {
• Finally, for part 3, look at the opening curly brace at the end of the line: {.
Now look at the bottom of the figure at part 4 of our code. This closing
curly brace } denotes the end of the class. Everything in between the
opening and closing curly braces, {…}, is part of the MainActivity class.
Methods inside the class
• Part 5 of the code: key part for code:
protected void onCreate(Bundle savedInstanceState) {
• Now jump to part 6 of code and will see a closing curly brace, }. Everything
in between the opening and closing curly braces of the onCreate method
is the code that executes when the method is called.
• Parts 7 and 8 are also methods named as onCreateOptionsMenu and
onOptionsItemSelected.
Examining the app layout file
Examining the app layout file
• In the project explorer window, left-click on the res folder and then left-click on
the layout folder. Now double left-click on the fragment_first.xml file. The XML
code contents of the file is now displayed in the main window of Android Studio.
• Left-click the Design button (shown next) to switch to the design view:
• Design view that shows the preview of execution of the XML code when
the app is run in the emulator:
The design view is a graphical representation of the XML code contained in the
fragment_first.xml file. Click on the Code tab (near the Design tab in the
previous figure) to see the XML code which forms the layout.
• 1 ConstraintLayout is a UI element that is used to






wrap other parts of the UI.
1b > Indicates end of ConstraintLayout attributes
3 TextView element.
4 /> indicate end of TextView element.
5 Button element.
6 /> indicate end of Button element.
2 > indicate end of ConstraintLayout element.
Adding buttons to the main layout file
Adding buttons to the main layout file
• Button can be added in two different ways: using the visual designer and by
editing the XML code directly.
• Adding a button via the visual designer
• Open fragment_first.xml in the editor and switch back to the design view by
clicking the Design tab
Palette window is opened on the left-hand side of the layout as shown
below.
• The palette is divided into two parts:
Categories of UI elements and available
UI elements in the currently selected
category.
• Select the Common category. Now, leftclick and hold on the Button widget and
then drag it onto the layout somewhere
near the top center.
• If the position of the button need to be
changed, then left-click it to select it on
the layout and then tap the Delete key on
the keyboard to get rid of it.
• Now repeat the previous step until a new
button is neatly placed
*Other operations to the main layout file:
• Editing the button’s attributes
• Examining the XML code for the new button
• Adding a button by editing the XML code
• Giving the buttons unique id attributes
• Positioning the two buttons in the layout
• Making the buttons call different methods
Coding messages to the user and the developer
• Two different classes from the Android API are used to output
• Log: allows to output messages to the Logcat window.
• Logcat Window is the place where various messages can be printed when an
application runs.
• Toast: produce a toast-shaped pop-up message for app’s user to see.
• Code to send a message to the Logcat window:
Log.i(“info”,”our message here”);
• Code to send a message to the user’s screen:
Toast.makeText(this, “our message”,
Toast.LENGTH_SHORT).show();
Writing first Java code
• Switch to the MainActivity.java tab in Android Studio.
• onCreate() method is called just before the app starts.
• Copy and paste some code into the onCreate() method
• Adding message code to the onCreate method
• Find the closing curly brace } of the onCreate method and add the
highlighted code shown next.
Thank You
College of Computing and Informatics
Bachelor of Science in Computer Science
IT448
Mobile Application Development
IT448
Mobile Application Development
Week 3
Exploring Android Studio and the Project Structure
Contents
1.Project Explorer and project anatomy.
2.Exploring the file and folder structure of the Empty Activity project
template.
3.Exploring the Android emulator.
Weekly Learning Outcomes
1. Demonstrate the Project Explorer and project anatomy.
2. Explain the Android emulator.
Required Reading
1. Chapter 3 (Android Programming for Beginners 3rd
Edition, 2021 by John Horton , Packt Publishing Ltd.)
Project Explorer and project anatomy.
Project Explorer and project anatomy
• Create new Android project – using a project template.
• Template is used to determine the exact selection and contents of files that
Android Studio will generate.
• Let’s build two template projects and examine the files, their contents, and how they are
all linked together through the code (Extensible Markup Language (XML) and Java).
• We begin by creating an Empty Activity project.
• Empty Activity project template is simplest project type with an autogenerated
UI.
• In Empty activity project template, the UI is almost empty, but it is there ready
to be added to (elements).
• When we create a project even with an empty UI, Android Studio also autogenerates
the Java code to display the UI.
Exploring the file and folder structure of the Empty Activity
project template.
 Select Start a new Android Studio project.
 On the Select a Project Template window, select Empty Activity.
 In the Configure your project screen, change the Name field to Empty Activity App.
 The rest of the settings can be left at their defaults, so just click Finish.
 Android Studio will generate all the code and the other project resources.
 Cross examine and verify if the generated details match with the contents that
appear in the Project Explorer window.
 Launch the emulator it by selecting Tools | AVD Manager in the Your Virtual
Devices window.
 Run the app on the emulator by clicking the play button in the quick launch bar
• The output appears as shown in the figure below.
• It is— well—empty  no menu at the top; no floating button at the bottom.
• Only Hello World!, text is displayed in the screen.
Exploring an Empty Activity project
• Now that we have a brand-new Empty Activity project, let’s explore the files and
folders that Android Studio has generated for us.
• In the following screenshot, look at the Project Explorer window as it is just after the
project is created:
• Notice the two arrows Enable to expand the app and Gradle Scripts folders.
Exploring an Empty Activity project
• Click the arrow next to the app folder to expand its contents.
• The first level of contents is shown in the following screenshot.
• Has generated four more folders: manifests, java, java(generated), and res.
Manifests folder
• Contains only one file inside it: AndroidManifest.xml
• AndroidManifest.xml is an XML file which contains
information about the Android app. This includes the
package name, activity names, main activity (the entry
point to the app), Android version support, hardware
features support, permissions, and other configurations.
Java folder
• Consists of only one file initially and three folders.
• Gets populated with more files as the project is
developed.
• Examine the MainActivity.java file, and you will see it is
a simplified version of the Java file.
• It has the onCreate method that executes when the app is
run by the user.
1
2
3
1 onCreate is called to start an activity/run the
application.
2 super.onCreate method tell the VM to run your
code in addition to the existing code in the
onCreate() of the parent class (AppCompatActivity)
3 setContentView sets the activity_main XML file you
want as your main layout when the app starts.
Java (generated) folder
• This folder contains code generated by
Android Studio.
The res folder
• Consists of all the resources for app such as
icons, layouts (XML files), sounds, and strings.
• res/drawable folder: holds just two
files(ic_launcher_foreground and
ic_launcher_background) along with the graphics
added to the project.
• The res/layout folder : Contains the layouts (XML
files.
The res/mipmap folder
• Consists of 2 subfolders: ic_launcher and
ic_launcher_round
1. ic_launcher are graphics for the app
launcher icon we see home screen of the
device.
2. ic_launcher_round are graphics for
devices that use the round icons.
The res/values folder:
• Consists of three files: colors.xml, string.xml, style.xml
• All these files interlink/refer to each other and/or other files.
• Colors.xml  defines the color to be displayed on the
screen.
• String.xml defines the name of the app created
• Styles.xml themes of android project is defined here
• Recent Android Studio versions call it themes.xml.
Exploring the Android emulator.
Emulator control panel
The mini control panel that appears beside the emulator when executed.
1. Window controls : minimize or close the emulator window.
2. Power off the emulator, simulating powering off the actual device. Two icons to
increase and decrease the volume.
3. Two buttons  to rotate the emulator left and right. Helps to visualize the
appearance of the app in different orientations.
4. Icons simulate the back button and home button, and viewing running apps.
5. This button is used launch the ADVANCED SETTINGS menu, to interact with
hardware such as sensors, the Global Positioning System (GPS), the battery,
the fingerprint reader, and more.
Using the emulator as a real device
• The emulator can emulate every feature of a real phone
Accessing the app drawer
• Hold the mouse cursor on the bottom of the home screen and drag upward to
access the app drawer (all the apps). The following screenshot shows this action
halfway through:
 Now, it can run any app installed on the emulator.
 when it runs one of apps through Android Studio, it
remains installed on the emulator and is therefore
runnable from the app drawer.
 Every change can make to the app in Android
Studio will require to run/install the app again by
clicking the play button on the Android Studio quick
launch bar.
Viewing active apps and switching between apps
• To view active apps, it can be used the emulator control panel, the square
labelled as number 4 on the screenshot of the emulator control panel
• To access the same option using the phone screen swipe up, just as when
accessing the app drawer.
• This process is illustrated in the following screenshot:
Swipe left and right through recent apps, swipe an app up to
close it, or tap the back button to return to what were doing
before viewed this option.
Thank You
‫الجامعة السعودية االلكترونية‬
‫الجامعة السعودية االلكترونية‬
‫‪26/12/2021‬‬
College of Computing and Informatics
Bachelor of Science in Computer Science
IT448
Mobile Application Development
IT448
Mobile Application Development
Week 4
Getting Started with Layouts the Project Structure
&
Beautiful Layouts with CardView and ScrollView
Contents
1.Finding out about Material Design
2.Exploring Android UI design
3.Introducing layouts
4.Building a precise UI with ConstraintLayout
5.Laying out data with TableLayout
6.Linking back to the main menu
7.Attributes quick summary
8.Building a UI with CardView and ScrollView
9.Creating a tablet emulator
Weekly Learning Outcomes
1. Explain the Android UI design and layouts.
2. Demonstrate the UI with CardView and ScrollView
Required Reading
1. Chapter 4 and Chapter 5 (Android Programming for
Beginners 3rd Edition, 2021 by John Horton , Packt
Publishing Ltd.)
Finding out about Material Design
Finding out about Material Design
• Objective of material design:
simple to create appealing UIs.
• *Material design is taken directly
from the design principles.
• Material design uses the concept of
layers of materials – similar to
photo-editing app
• Material design is a set of tools,
principles, rules, and guidelines 
consistency
Exploring Android UI design
• Android UI design is context-sensitive.
• *The way that a given widget’s x attribute will influence its appearance might depend
on a widget’s y attribute or even on an attribute on another widget.
• For example if you dragging and dropping widgets onto the design
• The Extensible Markup Language (XML) code that is generated will vary quite
considerably, depending upon type of the layout used.
• Different layout types use different techniques to identify the widget’s
position—for example, the LinearLayout is very differently from the
ConstraintLayout
• Here, we will see three types of layouts:
1. LinearLayout
2. ConstraintLayout
3. TableLayout
Introducing layouts
• Layouts are the building blocks that group together the other UI elements.
• Layouts can also contain other layouts.
• Layouts can be activated by setContentView method to work.
Creating and exploring a layout project
• Exploring Layouts project is the first app of this type,
1. Create a new project in Android Studio, select File | New Project. When
prompted, choose Open in same window.
2. Select the Empty Activity project template, click the Next button.
3. Enter Exploring Layouts for the application name and then click the Finish button.
Building a layout with LinearLayout
• LinearLayout is the simplest layout.
• All the UI items within it are laid out linearly.
• There are only two choices: vertical and horizontal.
Adding a LinearLayout layout type to a project
• Expand the res folder in the project window.
• Right-click the layout folder and select New.
• Select Layout resource file and the New Resource File dialog window will pop
up.
• In the Root element: field, enter LinearLayout.
• In the File name: field, enter main_menu. Click the OK button, and Android
Studio will generate a new LinearLayout in an XML file called main_menu and
place it in the layout folder, ready to build our new main menu UI. The new file is
automatically opened in the editor, ready for us to get designing.
*Adding LinearLayout to project
Building a precise UI with ConstraintLayout
Open the ConstraintLayout that was autogenerated when project is created.
It will be in the res/ layout folder. The filename is activity_main.xml.
Examine the XML in the Code tab : a TextView that says Hello World.
Switch back to the Design tab, left-click the TextView to select it, and tap the Delete key
to get rid of it.
Adding a CalendarView
Drag and drop the CalendarView from the widgets category of the palette, near the top
and horizontally central.
Resizing a view in a ConstraintLayout
• Left-click and hold one of the corner squares that are
revealed when let go of the CalendarView, and drag
inward to decrease the size of the CalendarView, as
illustrated in the following screenshot:
Reduce the size by about half and leave
the CalendarView near the top and
horizontally central. It might be needed to
reposition the widget resizing it. The result
should look like this:
Using the Component Tree window
• Component Tree window, the window to the left of the visual designer and below
the palette.
• A component tree is a way of visualizing the layout of the XML but without all the
details.
Adding constraints manually
• Select the CalenderView, the four small circles on the top, bottom, left, and right,
as illustrated in the following screenshot:
• These are the constraint handles. We can
click and drag them to anchor them with
other parts of the UI or the sides of the
screen. By anchoring the CalendarView
with the four edges of the screen, we can
lock it into position when the app is run.
Laying out data with TableLayout
TableLayout is building a layout that resembles a spreadsheet with neatly aligned cells with titles
and data.
Steps:
1.
In the project window, expand the res folder. Now, right-click the layout folder and select New.
2.
Select Layout resource file, the New Resource File dialog window will be seen.
3.
In the File name: field, enter my_table_layout. This is the same name which is used in the call to
setContentView within the loadTableLayout method.
4.
In the Root element: field that it has selected by default …ConstraintLayout as the option.
Delete …ConstraintLayout and type TableLayout.
5.
Click the OK button, and Android Studio will generate a new TableLayout in an XML file called
my_table_layout and place it in the layout folder, ready to build new table-based UI. Android
Studio will also open the UI designer with the palette on the left and the Attributes window on
the right.
6.
Now uncomment the loadTableLayout method in the MainActivity.java file
• Adding a TableRow element to TableLayout
• Drag and drop the TableRow widget from the component tree
Linking back to the main menu
Linking the table back to main menu
1. Add another TableRow via the Component Tree.
2. Drag a button onto the new TableRow.
3. Edit its layout_column attribute to 1 so that it is in the middle of the
row.
4. Edit its text attribute to Menu and edit its onClick attribute to match
already existing loadMenuLayout method.
Beautiful Layouts with
(Chapter
Attributes quick summary
CardView
and
ScrollView
5)
Chapter Objective
Learning of
different
attributes
Additional layouts
: Scrollview and
Cardview
Execute Cardview
project on Tablet
emulator
Attributes quick summary
Sizing using dp
• Example:
• density-independent pixels, or dp: unit of
• Consider a 2dp-by-2dp View element.
measurement.
• The same physical size is maintained on different
• Using density-independent measurements, we
resolution devices.
can design layouts that scale to create a uniform • Android maps dps to a different number of pixels.
appearance on as many different screen size
devices as possible.
• *Works is by calculating the density of the pixels
on the device an app is running on.
• *Used for setting size of various attributes of
widgets.
Sizing fonts using sp
• scalable pixels, or sp
• Device-dependent unit of measurement used for
sizing.
Determining size with wrap or match
• wrap and match use to size UI elements, and many other UI elements, behave in relation to
the containing/parent element.
• Done by setting the layoutWidth and layoutHeight attributes to either wrap_content or
match_parent. (LinearLayout)
• For example, say we set the attributes of a button on a layout to the following. Then, the button
will expand in both height and width to match the parent.
Using padding and margin
• Padding is the space from the edge of the widget to the start of the content in the widget.
• Margin is the space outside of the widget that is left between other widgets – including the
margins of other widgets, as shown in figure:
• We can set the padding and margin in a straightforward
way, equally for all sides, like this:
• Alternatively, we can specify different top, bottom, left,
and right margins and paddings, like this:
Using the layout_weight property
• The layout_weight specify the size of child views in a container.
• For example, if we want to place two buttons horizontally by occupying each half of the screen width, we can
define layout weight as 0.5 for each button inside the Layout.
• *Divide the screen space among the parts of the UI elements.
• *To maintain uniformity in the relative space occupied by the UI elements on the screen
independent of the device.
• *layout_weight is used in conjunction with sp and dp units for a simple and flexible layout.
The UI with the layout_weight property in use
Gravity
• Gravity affects the position of items by moving them in a given
direction.
• Example:
android:gravity=”left|center_vertical”
• The element content is left aligned horizontally and in center
aligned vertically.
• To position the layout itself, gravity will be defined as:
android:layout_gravity=”left”
Building a UI with CardView and ScrollView
ScrollView
• A ScrollView elements allows users to scroll through a
list of views that occupy more space than the physical
display.
• Create a new project in the usual way and choose the
Empty Activity project template. Name the project
ScrollView Layout.
• Right-click the layout folder and select New.
• Select Layout resource file the New Resource File
dialog window will be shown.
• In the File name field, enter scrollview.
• In the Root element: field that it has selected by default
…ConstraintLayout as the option. Delete
…ConstraintLayout and type ScrollView.
• Now, drag LinearView from palette to scrollview.xml file
and place some button elements inside it.
CardView
• CardView is a very powerful UI tool. You may add photo, texts,
links etc in a card to give your user one nice representation of
the information you want to share.
Adding image resources
• Images are added and formatted in a CardView widget
1. Find the picture files using operating system’s file browser and copy them.
2. Highlight them all and press Ctrl + C to copy them.
3. In the Android Studio project explorer, select the res/drawable folder
4.
Right-click the drawable folder and select Paste.
5. In the pop-up window that asks Choose Destination Directory, click OK to accept the
default destination the drawable folder.
6. Click OK again to Copy Specified Files.
Creating a tablet emulator
• Select Tools | AVD Manager and then click the Create Virtual Device… button on the
Your Virtual Devices window. Select Hardware window pictured next.
• Select the Tablet option from the Category list, and then highlight the Pixel C tablet from
the choice of available tablets
Thank You
‫الجامعة السعودية االلكترونية‬
‫الجامعة السعودية االلكترونية‬
‫‪26/12/2021‬‬
College of Computing and Informatics
Bachelor of Science in Computer Science
IT448
Mobile Application Development
IT448
Mobile Application Development
Week 5
The Android Lifecycle
Contents
1.The life and times of an Android app
2.How Android interacts with our apps
3.A simplified explanation of the Android lifecycle
4.How we handle the lifecycle phases
5.Lifecycle demo app
6.Examining the lifecycle demo app output
7.Some other overridden methods
8.The structure of Java code – revisited
9.Introducing fragments and the lifecycle
Weekly Learning Outcomes
1. Explain the Android Lifecycle phases..
2. Explain how handle the Android Lifecycle phases.
Required Reading
1. Chapter 6 (Android Programming for Beginners 3rd
Edition, 2021 by John Horton , Packt Publishing Ltd.)
The life and times of an Android app
The lifecycle of an Android app
• Lifecycle: the way that all Android apps interact with the Android OS.
• The phases of the lifecycle is the stages an app goes through from creation to destruction.
• The phases of the lifecycle helps to know where to put our Java code, depending on the objective
of the app.
• Topics covered n this chapter:
 The life and times of an Android app
 What is method overriding
 The phases of the Android lifecycle
 What exactly we need to know and do to code our apps
 A lifecycle demonstration mini app.
 A quick look at code structure
Exploring Android UI design How Android interacts with
our apps
How Android interacts with apps
• It does so by calling methods that are contained within the Activity class:
• Called by Android when required.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
• @Override: It tells the Android that the following onCreate method overrides a method of its
superclass.
• onCreate method starts an activity in android.
• super.onCreate(savedInstanceState)
• Directs Android to invoke the original version of the onCreate method before proceeding with our overridden
version.
• setContentView is used to set the activity_main xml layout on the screen.
A simplified explanation of the Android lifecycle
Android lifecycle phases
• Android system has multiple distinct phases.
• The phase of the Android system decides how the app is viewed by the user – *or
whether it is viewed at all.
• Resources such as memory and processing power is allocated by Android based
on the phase of the android app life cycle.
• Every app on an Android device will in one of the following phases:
1.
2.
Being created
Starting
3.
Resuming
4.
5.
Running
Pausing
6.
7.
Stopping
Being destroyed
Example – Facebook to email app
• When a user presses facebook app icon, the app is created and started
• After starting the app it is then in resuming stage.
• After resuming, the app is running. This is when the Facebook app has control of
the screen and the greater share of system memory and processing power and is
receiving the user’s input.
• When switching over from facebook app to an email app, facebook app would
move into paused stage, then into stopping stage.
• The email app will get into created started resuming and running stage.
• If we decide to revisit Facebook, the Facebook app will skip being created and go
straight to resuming and then be running again.
• Note that at any time, Android can decide to stop then destroy an app.
• When an app gets into stop or destroy stage, it has to start over again.
Android lifecycle phases
• Android applications don’t start with a call to main(String[])
• Instead, a series of callback methods are invoked by the
Android OS
• Each corresponds to specific stage of the Activity / application
lifecycle
• Callback methods also used to tear down Activity / application
How we handling the lifecycle phases
• An Android activity is one screen of the Android app’s user interface.
• An Android app may contain one or more activities  one or more screens.
• The Android app starts by showing the main activity, and from there the app may
make it possible to open additional activities.
• All activities in android apps are represented by an activity class
• Activity classes are subclasses of androidx.appcompat.app.AppCompatActivity
• Android provides us with a set of methods to manage the lifecycle phases of app.
• Android code that was autogenerated when we created our first project does
most of phases for us.
• *Autogenerated codes can be overridden to customize the code according to
requirement.
How we handling the lifecycle phases
• onCreate: first method is executed when the activity is
being created.
• Declare the UI setContentView, graphics, sound
• onStart: This method is executed when the app is in
the starting phase.
• Makes the activity visible to the user, as the app
prepares for the activity to enter the foreground and
become interactive
• This method is where the app initializes the code that
maintains the UI.
• onResume: This method runs after onStart.
• It is also invoked after the app being previously paused.
• Reloads the previously saved user data from when the
app was interrupted, a phone call or the user running
another app.
Activity Life cycle- Flow of Execution of methods
How we handling the lifecycle phases
• onPause: This method is callback when the app is
pausing.
• The app would pause when the device goes to
sleep or when the user ABOUT TO switches to
another app, another activity, pop-up dialog.
• The unsaved data will be saved and will be
reloaded in onResume
• onStop: This relates to the stopping phase. It
preforms tasks such as releasing system resources or
writing information to a database. Called when:
• User starts another activity in the application.
• User starts a new application
• User receives phone call
• onDestroy: This is when activity is finally being
destroyed. The application is removed from the
memory. Used to kill long running resources.
Activity Life cycle- Flow of Execution of methods
Activity Life
cycle- Flow of
Execution of
methods
Lifecycle demo app
Lifecycle demo app
• Here, we will familiarize ourselves with life cycle methods of an app.
• Follow these steps to start a new project and then we can add some code:
1. Start a new project.
2. Choose the Basic Activity template.
3. Call the project Lifecycle Demo.
4. Wait for Android Studio to generate the project files and then open the
MainActivity.java file in the code editor.
Coding the lifecycle demo app
Running the lifecycle demo app
Coding the lifecycle demo app
• In the MainActivity.java file, find the onCreate method and add these two lines of code just
before the closing curly } brace, which marks the end of the onCreate method:
Toast.makeText(this, “In onCreate”, Toast.LENGTH_SHORT).show();
Log.i(“info”, “In onCreate”);
• After the closing curly brace, }, of the onCreate method, leave one clear line and add the
following five lifecycle methods (shown in next slide) and their contained code.
• Android will call these methods irrespective of the order in the code.
Life cycle methods code listing
@Override
public void onStart() {
// First call the “official” version of this method
super.onStart();
Toast.makeText(this, “In onStart”,
Toast.LENGTH_SHORT).show();
Log.i(“info”, “In onStart”);
}
@Override
public void onResume() {
// First call the “official” version of this method
super.onResume();
Toast.makeText(this, “In onResume”,
Toast.LENGTH_SHORT).show();
Log.i(“info”, “In onResume”);
}
@Override
public void onPause() {
// First call the “official” version of this method
super.onPause();
Toast.makeText(this, “In onPause”,
Toast.LENGTH_SHORT).show();
Log.i(“info”, “In onPause”);
}
@Override
public void onStop() {
// First call the “official” version of this method
super.onStop();
Toast.makeText(this, “In onStop”,
Toast.LENGTH_SHORT).show();
Log.i(“info”, “In onStop”);
}
@Override
public void onDestroy() {
// First call the “official” version of this method
super.onDestroy();
Toast.makeText(this, “In onDestroy”,
Toast.LENGTH_SHORT).show();
Log.i(“info”, “In onDestroy”);
}




@Override keyword  methods replace/override the original
version of the method that is provided as part of the Android API.
The super.on…, : the first line of code within each of the
overridden methods, then calls these original versions
Output of the added code: output one Toast message and one
Log message.
The only code, however, that put in these methods was a few calls
using Toast and Log.
Running the lifecycle demo app
1. Run the emulator
2. “Toast” messages will appear on the screen for every life cycle methods
in the order In onCreate  In onStart  In onResume.
3. LogCat  view the system log
4. Following messages obtained in LogCat window
5. On tapping the back button on the emulator, “Toast” message will appear
in the order In onPause  In onStop  In onDestroy
Examining the lifecycle demo app output
Examining the lifecycle demo app output
• When the lifecycle demo app started for the first time: the onCreate, onStart, and onResume
methods were called.
• When the app is closed using the back button, the onPause, onStop, and onDestroy methods
were called.
• *When switching away and switching to the lifecycle demo was not necessary to run onCreate.
• Calling of lifecycle methods vary in different device according to the different users preferences,
and hence the methods calling sequence cannot be predicted.
• The solution to all this complexity is to follow a few simple rules:
1. Set up app ready to run in the onCreate method.
2. Load user’s data in the onResume method.
3. Save user’s data in the onPause method.
4. Tidy up the app and make it a good Android citizen in the onDestroy method.
Some other overridden methods
 Basic Activity Template in the Android Project has 2 other autogenerated code:
onCreateOptionsMenu and onOptionsItemSelected
 Auto generated code for pop-up menu
 onCreateOptionsMenu: Load the menu from the menu_main.xml
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
 onOptionsItemSelected method is called when the user taps the menu button.
• Directs the execution to the item selected
• just returns true when nothing happens.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
The structure of Java code – revisited
• Package: Container for the user defined code and libraries
• Classes: the building blocks of code
• Methods: wrap the functional code that does the work.
• Methods can be written within the classes that can be extended.
Introducing fragments and the lifecycle
• MainActivity.java : Contains the basic activity template along with 
Firstfragment.java and SecondFragment.java files
• Contains the code to handle the navigation of the user between the screens of the
BasicactivityTemplate
• Fragment is the part of activity; it is also known as sub-activity.
• Fragment is a class like an activity in a class.
• There can be more than one fragment in an activity.
• Fragments represent multiple screen inside one activity.
 Controlled by Activity classes
 Has its specific lifecycle methods
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
Thank You
‫الجامعة السعودية االلكترونية‬
‫الجامعة السعودية االلكترونية‬
‫‪26/12/2021‬‬
College of Computing and
Informatics
Bachelor of Science in Computer
Science
IT448
Mobile Application Development
IT448
Mobile Application Development
Week 6
Android Dialog Window, Adapters and Recyclers
Contents
1.Dialog windows.
2.RecyclerView and RecyclerAdapter.
3.Adding RecyclerView, RecyclerAdapter.
4.Running the app.
Weekly Learning
Outcomes
1. Explain how to use Android Dialog windows in
app.
2. Explain how to use RecyclerView and
RecyclerAdapter.
Required Reading
1. Chapter 14 & Chapter 16 (Android Programming for
Beginners 3rd Edition, 2021 by John Horton , Packt
Publishing Ltd.)
Dialog windows
Dialog window
• Dialog window is pop-up window to display notification or confirmation messages to the user.
• Dialogs in Android are sophisticated classes that consists of layouts and other specific User
Interface (UI) elements.
• The best way to create a dialog window in Android is to use the DialogFragment class.
• Creating the Dialog Demo project: create a new project in Android Studio named “Dialog
Demo” with Empty Activity template.
• Coding a DialogFragment class: Create a new JAVA class and refer it as “MyDialog” in same
package that has the MainActivity.java file.
• Change the class declaration to extend DialogFragment
public class MyDialog extends DialogFragment {
}
• Import the DialogFragment class: Add the code in the MyDialog.java file
package com.example.dialogdemo;
import androidx.fragment.app.DialogFragment;
public class MyDialog extends DialogFragment {
}
Dialog window
• Add the following highlighted code to override the onCreateDialog method
public class MyDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class because this dialog has a simple UI
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
}
}
• You will need to import the Dialog, Bundle, and AlertDialog classes
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
• The onCreateDialog method will be called by Android via code in the MainActivity class.
• Declare and Initialize AlertDialog.Builder object.
• The getActivity method is part of the Fragment / DialogFragment class and it returns a
reference to Activity, which will create DialogFragment. In this case, that is our
MainActivity class.
Configure DialogFragment: Chaining
• Chaining: is the process of calling more than one method in a sequence (single
line) on the same object instead of calling multiple methods with the same object
reference separately.
• Similar to writing multiple lines of code in a concise manner.
• Example: When a Toast message is created and added a .show() method to
the end of it.
Toast.makeText (this, “our message”, Toast.LENGTH_SHORT).show(); // with
chaining (1 line)
Toast toast = Toast.makeText (this, “Hello”, Toast.LENGTH_SHORT);
chaining ( 2 lines)
toast.show();
// Without
Configure DialogFragment: Chaining
• Add the code (which uses chaining) inside the onCreateDialog method
// Dialog will have “Dialog Window” as the title
builder.setMessage(“Dialog Window”)
// An OK button that does nothing
.setPositiveButton(“OK”, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Nothing happening here
}
});
// Create the object and return it
return builder.create();
• Import the Dialog interface class
import android.content.DialogInterface
• Builder.setMessage: sets the main message for the user in the dialog window.
• .setPositiveButton: sets the “OK” as the text of the button which is the argument in this
method.
• DialogInterface.onClickListener: handles any click on the button.
• return statement: takes the control to MainActivity class.
• Then, fully configured dialog window is created.
Using the DialogFragment class
• Add a button to our layout. Perform the following steps:
1. Switch to the activity_main.xml tab and then switch to the Design tab.
2. Drag a Button onto the layout and set its “id” attribute to button.
3. Click on the Infer Constraints button to constrain the button in the location to be placed.
• onClick method creates a new
4. Adding the following code to onCreate method
instance of MyDialog and calls its
Button button = (Button) findViewById(R.id.button);
show method.
button.setOnClickListener(
• The show method needs a
new View.OnClickListener() {
reference to FragmentManager
@Override
class, which we can get with
public void onClick(View v) {
getSupportFragmentManager
MyDialog myDialog = new MyDialog();
myDialog.show(getSupportFragmentManager(),
“123”);
method.
);
}
}
• *FragmentManager is a class that
tracks and controls all Fragment
instances for an activity.
• *getSupportFragmentManager: is
uses to support older devices by
extending the AppCompatActivity
class
• We also pass in an identifier: “123”.
Using the DialogFragment class
• classes to import for this code:
import android.view.View;
import android.widget.Button;
• Output of the code:
String Resources
• In Android, almost everything is a resource.
• *Defining resources that you can then access in your app is an essential part of Android
development.
• Resources are used for anything from defining colors, images, layouts and string values.
• Everything is defined in resource files and then can be referenced within your application’s
code.
• For every piece of text you want to display within your application (i.e the label of a button, or
the text inside a TextView), you should first define the text in the res/values/strings.xml
file.
• Each entry is a key (representing the id of the text) and a value (the text itself).
• For example, if I want a button to display “Click Me”, I might add the following string resource to
res/values/strings.xml:
My Application

Still stressed from student homework?
Get quality assistance from academic writers!

Order your essay today and save 25% with the discount code LAVENDER