0% found this document useful (0 votes)
20 views389 pages

IT448 New Slide

The document outlines the curriculum for IT448: Mobile Application Development, focusing on the integration of Java and Android, and the setup of Android Studio. It covers the basics of Android programming, including the Android API, object-oriented programming concepts, and the steps to build an Android app. Weekly learning outcomes emphasize understanding project structure and utilizing the Android emulator.

Uploaded by

xxsamixx96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views389 pages

IT448 New Slide

The document outlines the curriculum for IT448: Mobile Application Development, focusing on the integration of Java and Android, and the setup of Android Studio. It covers the basics of Android programming, including the Android API, object-oriented programming concepts, and the steps to build an Android app. Weekly learning outcomes emphasize understanding project structure and utilizing the Android emulator.

Uploaded by

xxsamixx96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 389

College of Computing and Informatics

Bachelor of Science in Computer Science

IT448: Mobile Application Development


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 2 (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 to provide functionalities for 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 even faster for the device by ART.
• ART system: provides hooks into application and enhance memory
management while the application is running -> app run more efficiently.

Compile when the user install


the java the application, Android
file to a Runtime (ART) convert
bytecode the bytecode into
understo machine code (binary or
od by hexadecimal
Android instructions)
Understanding the Android API
Understanding the Android API &

Android API (Application Programming Interface): The Android API has a whole bunch
of Java code that has already been written for us to use as we like. A simple analogy
could be drawn with a car. When you press on the accelerator, a whole bunch of
things happen under the hood. We don't need to understand combustion or fuel
pumps because some smart engineer has made an interface for us (a mechanical
interface: the accelerator pedal).
The interface The functionalities

Have a powerful and complicated function, with


This single line of code the help of Android API
locationManager.getLastKnownLocation Searches for available satellites in space, and then communicates
(LocationManager.GPSPROVIDER) with them in their orbits around the Earth, then retrieves your
preciselatitude and longitude on the surface of the planet.
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.
object-oriented String color;
&

programming String make;


String model;
(OOP) concept. int year;

Car
Objects object1 object2 object3
color=“Green” color=“red” color=“Blue”
(instances) make=“Ford” make=“Nissan” make=“BMW”
model=“Expedition” model=“Sunny” model=“X1”
year=2019 year= 2010 year=2016
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 (Central Processing Unit (CPU), Graphics Processing Unit (GPU) , Global
Positioning System (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. Android Application Package (APK): is the executable file of an
android application that can be installed on any android device.

• *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:
✓ Java Development Kit (JDK): To use/write Java code
✓ Android Software Development Kit (SDK) : Collection of tools for
Android development and Android APIs.
• Tasks by Android Studio
✓ Provides an IDE (Integrated Development Environment)
✓ Compiling code.
✓ Linking with the JDK and the Android API
Setting up Android Studio
1. Create a new folder on the root of C or D drive called Android. Inside the
Android folder, create:
1. New folder called Android Studio.
2. New folder called Projects, to keep all the project files.
3. New folder called SDK, to install the Android SDK.

You Should now have a D:\Android folder that looks like this:
Setting up Android Studio
2. Download Android Studio from https://developer.android.com/studio
3. Once the download is complete, find the downloaded file and double-left-click the
file to run it.
4. 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:

2
4

3
Setting up Android Studio
5. 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
6. 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.
7. Once getting the Installation Complete message, left-click the Next button, then left-
click the Finish button.
8. When prompted about importing android sStudio Settings, choose “Do not import
settings”.
6
8
Setting up Android Studio
9. click “Don’t send”. Then click “Next”. Then click “Next”.
Setting up Android Studio
10. Select your UI them, dark or light, then click “Next”
11. On Verify Settings, click “Next”.

10 11
Setting up Android Studio
12. To move on, choose “Accept” to all the Licenses (not just one). Then Choose
“Finish”.
13. Click “Finish”.

12 13
Setting up Android Studio
13. Upon completion, you will see Android Studio welcome screen, as shown in the
following screenshot.
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. Click on “Projects" option on the
left menu, then click on “New
Project”.
Building our first Android app
5. The window that follows is to 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:
Building our first Android app
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.
e. Click “Finish”.
8. The next screenshot shows the Configure Your Project
screen once you have entered all the information.
Building our first Android app
Wait for the project to be build completely.
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, left-
click 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.
Installing and running The Emulator
Run Java code using the Emulator
You need to install a virtual device to use it as an emulator when you run your app
1. Go to Tools> Device Manager
2. In the Device Manager window, choose Virtual>click on Create Device.
3. Choose a device of your choice. Then click Next.
4. Choose a System image of your device and download. Then click Finish.
5. After adding a device and its system into the device manager (for example, Device: Pixel 4, System:
UpsideDownCake), Next to your chosen device click Run to Launch the emulator.
6. The emulator screen will show your device up and running.
7. Now you can run your app (your java code) on the emulator by clicking the play button in the quick launch bar.

5 7
2
1
6
3 4
Output (After Running Java code using the Emulator)
Toast.makeText(this,"our message",Toast.LENGTH_SHORT).show();
Log.i("info","our message here");
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 (ch3)
Contents
1.Project Explorer and project anatomy.
2.Exploring the file and folder structure of the Empty Activity project
template.
3.Exploring the file and folder structure of the Basic Activity project
template.
4.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 User Interface (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 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
1 activity_main XML file you want
2 as your main layout when the app
3
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 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. Being created
2. Starting
3. Resuming
4. Running
5. Pausing
6. Stopping
7. Being destroyed
Starting Activities

• 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
Simplified Lifecycle Diagram
ready to interact
with user

The Android OS
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 @Override
public void onStart() { public void onStop() {
// First call the "official" version of this method // First call the "official" version of this method
super.onStart(); super.onStop();
Toast.makeText(this, "In onStart", Toast.makeText(this, "In onStop",
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
Log.i("info", "In onStart"); Log.i("info", "In onStop");
} }
@Override @Override
public void onResume() { public void onDestroy() {
// First call the "official" version of this method // First call the "official" version of this method
super.onResume(); super.onDestroy();
Toast.makeText(this, "In onResume", Toast.makeText(this, "In onDestroy",
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
Log.i("info", "In onResume"); Log.i("info", "In onDestroy");
} }
@Override
• @Override keyword → methods replace/override the original
public void onPause() {
version of the method that is provided as part of the Android API.
// First call the "official" version of this method • The super.on..., : the first line of code within each of the overridden
super.onPause();
methods, then calls these original versions
Toast.makeText(this, "In onPause",
• Output of the added code: output one Toast message and one
Toast.LENGTH_SHORT).show();
Log message.
Log.i("info", "In onPause");
• 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 Basic
Activity Template.
• 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); // Without chaining ( 2 lines)
toast.show();
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.
4. Adding the following code to onCreate method • onClick method creates a new
Button button = (Button) findViewById(R.id.button); instance of MyDialog and calls its
button.setOnClickListener( show method.
new View.OnClickListener() { • The show method needs a reference
@Override to FragmentManager class, which we
public void onClick(View v) { can get with
MyDialog myDialog = new MyDialog(); getSupportFragmentManager
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:
<resources>
<string name="app_name">My Application</string>
<string name=“buttonText">Click Me</string>
</resources>
• If we reference the string resource for buttonText, the default will be for “Click Me" to be
displayed.
String Resources and Naming Conventions
• Naming conventions: are the conventions or rules used for naming the variables, methods,
and classes in the code.
• When a variable is a member of a class, name of the variable is prefixed with a lowercase m.
• String Resources: used to avoid hardcoding text in user layouts.
Adapters and Recyclers (Chapter 16)
Objectives
• Looking at the theory of adapters and binding them to our UI
• Implementing the layout with RecyclerView
• Laying out a list item for use in RecyclerView
• Implementing the adapter with RecyclerAdapter
• Binding the adapter to RecyclerView
• Storing notes in ArrayList and displaying them in RecyclerView
Problem with displaying lots of widgets
• A ScrollView elements allows users to scroll through a list of views that
occupy more space than the physical display.
• ScrollView can be used to populate view such as CardView and
TextView widgets.
• Example: We could create the TextView widgets dynamically in
Java code and then add the TextView widgets to a LinearLayout
contained in a ScrollView. However, this is imperfect.
• Imagine you have a list of 1000 items and you want to show them in a
scrollable list in your application, if you use a ScrollView, it creates 1000
views at once and will keep all of them in memory.
• This approach can cause a memory leak or at least the user won’t
be able to scroll items smoothly.
• Android device might simply run out of memory: handling the
scrolling of a vast number of widgets and their data. ScrollView
Solution to the problem of displaying lots of widgets-RecyclerView
• *The display of elements in a list or grids is a very common pattern in mobile applications.
• The user sees a collection of items and can scroll through them.
• The collection of items can be a list, a grid, an array or another structured representations of data.
• RecyclerView widget makes it easy to efficiently display large sets of data.
• RecyclerView widget is a container for displaying large data sets that can be scrolled very
efficiently by maintaining a limited number of views.
• This improvement is achieved by recycling the views which are out of the visibility of the user.
• For example, if a user scrolled down to a position where items 4 and 5 are visible; items 1, 2,
and 3 would be cleared from the memory to reduce memory consumption.
Solution to the problem of displaying lots of widgets-RecyclerView
1. Add a single widget called RecyclerView (Like ScrollView) to the UI
layout.
2. Interact with RecyclerView with a special type of class called
RecyclerAdapter class.
3. Extend and customize RecyclerAdapter class, to control the data
from ArrayList instance and Display it in RecyclerView.
Create a RecyclerView
• To display data in a RecyclerView, you need the following items:
1. Data to display: create the data locally through List, ArrayList, database.
2. RecyclerView: for the scrolling list that contains data.
3. Layout manager It manages the arrangement of data contained within RecyclerView. This
layout manager could be vertical, horizontal, or a grid. You will use a vertical
LinearLayoutManager.
4. Item Layout: Its layout filled with one item of data from ViewHolder.
5. An adapter. Use an extension of RecyclerView.Adapter to connect your data to the RecyclerView.
It prepares the data item and how will be displayed in a ViewHolder. *When the data changes, the
adapter updates the contents of the respective list item view in the RecyclerView.
6. A ViewHolder. Use an extension of RecyclerView.ViewHolder to contain the information for
displaying one View item using the item's layout.
Activity Adapter Data
RecycleView
LayoutManager ViewHolder Item

Item Layout
Create a List in Android using RecyclerView
• First of all, create a new Android Project in Android Studio and select Empty Activity for
now. Name the project RecycleViewExample.
• Go to activity_main.xml and write the following code in it. Here, we have added a
RecyclerView to the view hierarchy inside LinearLayout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_course"
android:layout_height="match_parent"
android:layout_width="match_parent"
/>
</LinearLayout>
Create a List in Android using RecyclerView
• Creating a new class named Course.java.
• Objects of this class will contain the data fields which
we want to store and display in the RecyclerView.
• Now write the following code in the Course.java class.
public class Course {
private String mCourse_name;
private String mCourse_id;
private String mCourse_time; • The Course class has attributes: mCourse_id,
public Course(String cid, String cname, String ctime) { mCourse_name, mCourse_time
this.mCourse_id = cid; • These attributes represents course id, course name
this.mCourse_time = ctime;
and course time fields of data item.
this.mCourse_name = cname;
} • public Course(String cid, String cname, String ctime) is
public String getmCourse_name() { class constructor.
return mCourse_name; • getmCourse_id(), getmCourse_name() and
}
public String getmCourse_id() { getmCourse_time() are three methods uses to return
return mCourse_id; the value of the attributes.
}
public String getmCourse_time() {
return mCourse_time;
}
}
Create a List in Android using RecyclerView-view
• Now, create a row layout file to contain a view of data item inside the RecyclerView.
• Create a new layout file named row_course.xml and write the following code in it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">

<TextView
android:id="@+id/txt_course_name"
android:layout_width="match_parent" view
android:layout_height="wrap_content"
android:text="txt_course_name"
android:textColor="@android:color/black"
android:textSize="22sp" />

<TextView
android:id="@+id/txt_course_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="txt_course_id"
android:textSize="22sp" />

<TextView
android:id="@+id/txt_course_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="txt_course_time"
android:textSize="18sp" />

<TextView
android:id="@+id/border_line"
android:layout_width="398dp"
android:layout_height="2dp"
android:layout_alignParentBottom="true"
android:background="#808080" />
</LinearLayout>
Create a List in Android using RecyclerView - ViewHolder
• Now, we will create a ViewHolder class.
• ViewHolder is a class which holds the data items that is to be shown in the UI for each view
inside the RecyclerView.
• Create a new class named CourseViewHolder.java and write the following code in it.
public class CourseViewHolder extends RecyclerView.ViewHolder { //1 1. CourseViewHolder extend the RecyclerView.ViewHolder to
private TextView mtxtCourseName; //2 contain the information for displaying one View item using
private TextView mtxtCourseId; the item's layout.
private TextView mtxtCourseTime;
public CourseViewHolder(View itemView) { //3 2. Three local variables for course name, course id, and
super(itemView); course time to reference txt_course_name, txt_course_id and
mtxtCourseName = itemView.findViewById(R.id.txt_course_name); txt_course_time widgets inside of java class.
mtxtCourseId = itemView.findViewById(R.id.txt_course_id); 3. Class contractor initializes the CourseViewHolder by calling
mtxtCourseTime = itemView.findViewById(R.id.txt_course_time); the super of RecyclerView.ViewHolder. Then, it make a
}
public void setCourseName(String courseName) { // 4
reference to the three widgets of row_course.xml layout
this.mtxtCourseName.setText(courseName); inside of the class.
} 4. setCourseName, setCourseID and setCourseTime uses to fill the
public void setCourseID(String courseId) { view of RecyclerView with the data items; course name,
this.mtxtCourseId.setText(courseId); course id and course time.
}
public void setCourseTime(String courseTime) {
this.mtxtCourseTime.setText(courseTime);
}
}
Create a List in Android using RecyclerView - adapter
• *Views and Data sources are different things. They need an interface to communicate with each other.
• Adapter is a just a class which is tasked to act as a bridge between the data item and the view inside of
RecycleView.
• It works as a iterator and picks one data item from the data source and shows it into the View using the
ViewHolder until all the data items are traversed.
• To achieve this, create a new Java class named CourseAdapter.java and write the following
code in it.
public class CourseAdapter extends RecyclerView.Adapter <CourseViewHolder> {
private Context context;
private ArrayList<Course> courseList;
public CourseAdapter(Context context, ArrayList<Course> courseList) { // contractor
this.context = context;
this.courseList = courseList;
}
}
• *The Adapter class has two members — namely courseList of type ArrayList which will contain
the data that needs to be loaded in the view and context which is the context of the Activity that
uses the adapter object.
Create a List in Android using RecyclerView - adapter
• After that, you will notice an error in the class header. We need to implement the default
RecyclerView methods, Click in the class header. It will show an option named “Implement
methods”, click on it. Then, you will find 3 methods as “onCreateViewHolder()”,
“onBindViewHolder()” and “getItemCount()” in popup menu. Click OK to auto-generate the required
methods.
Create a List in Android using RecyclerView - adapter
• This process adds the following three methods:
• onCreateViewHolder(): RecyclerView calls this method whenever it needs to create a new
ViewHolder to represent data item. The method creates and initializes the ViewHolder and its
associated View.
• onBindViewHolder(): RecyclerView calls this method to associate a ViewHolder with data item.
The method fetches the appropriate data and uses the data to fill in the view holder's layout.
• getItemCount(): RecyclerView calls this method to returns the total number of items in the data
set held by the adapter. RecyclerView uses this method to determine when there are no more
items that can be displayed. Initially it returns 0.
@Override
public CourseViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
return null;
}

@Override
public void onBindViewHolder( CourseViewHolder holder, int position) {
}

@Override
public int getItemCount() {
return 0;
}
}
Create a List in Android using RecyclerView - onCreateViewHolder()
• Add the following code inside onCreateViewHolder()
• The onCreateViewHolder() method is similar to the onCreate() method. It inflates the item
row_course layout, and returns a ViewHolder with the layout and the adapter.
• LayoutInflater reads a layout XML description and converts it into the corresponding View items.

@Override
public CourseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_course, parent, false);
return new CourseViewHolder(view);
}
Create a List in Android using RecyclerView - onBindViewHolder()
• Add the following code inside onBindViewHolder()
• The onBindViewHolder() method connects your data to the ViewHolder.
• It associates the data item with the ViewHolder for a given position in the RecyclerView.
• This method is called iteratively for every item in the list and we need to define here what to do with
our data. In our example, we retrieve the data for RecyclerView position that is to be shown in the UI
for each view inside the RecyclerView using setCourseName, setCourseName and setCourseID
methods.
@Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
Course course = courseList.get(position);
holder.setCourseName(course.getmCourse_name());
holder.setCourseName(course.getmCourse_id());
holder.setCourseID(course.getmCourse_time());
}
Data item onBindViewHolder row_course.xml layout
Create a List in Android using RecyclerView - getItemCount()
• Add the following code inside getItemCount()
• The getItemCount() returns to number of data items available for displaying in courseList.

@Override
public int getItemCount() {
return courseList.size();
}
Create a List in Android using RecyclerView - MainActivity
• Add the following code inside of MainActivity
• MainActivity class has two members:
• courseList which we want to hold the list of course objects and
• rvCourse which is just an object of RecyclerView type (used to handle operations on RecyclerView).

public class MainActivity extends AppCompatActivity {


private ArrayList<Course> mCourseList;
private RecyclerView rvCourse;

• Then, Add the following code inside of onCreate method

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
generateData();
setData();
}
Create a List in Android using RecyclerView - MainActivity
• Add the following method inside of MainActivity
private void init() {
mCourseList = new ArrayList<>();
rvCourse = findViewById(R.id.rv_course);
}

• This init() method initializes the class members courseList and rvCourse with their a new
ArrayList and RecyclerView respectively.
Create a List in Android using RecyclerView - MainActivity
• Add also the following method inside of MainActivity

private void generateData() {


mCourseList.add(new Course("Mobile Application Development", "IT448", "4:00 PM - 5:00 PM"));
mCourseList.add(new Course("Web Design", "IT404", "5:00 PM - 6:00 PM"));
mCourseList.add(new Course("Computer Organization", "IT233", "6:00 PM - 7:00 PM"));
mCourseList.add(new Course("Business Computer Languages", "IT401", "7:00 PM - 8:00 PM"));
mCourseList.add(new Course("Computer Networks", "IT210", "8:00 PM - 9:00 PM"));
mCourseList.add(new Course("Operating Systems", "IT241", "9:00 PM - 10:00 PM"));
}

• In generateData() method, we added some sample course data to the courseList which we’ll use
in our adapter.
Create a List in Android using RecyclerView - MainActivity
• Add also the following method inside of MainActivity

private void setData() {


rvCourse.setLayoutManager(new LinearLayoutManager(this));
rvCourse.setAdapter(new CourseAdapter(this, mCourseList));
}

• In setData() method, we set a LayoutManager for RecyclerView.


• As we mentioned before, LayoutManager is used in the RecyclerView to position items accordingly.
Specifically, LinearLayoutManager sets items linearly.
• In our example, we used LinearLayoutManager because we want to display list in linearly and this
layout manager has vertical view as default.
• In this method, we set an adapter. Use an extension of RecyclerView.Adapter to connect your data to
the RecyclerView.
Create a List in Android using RecyclerView - MainActivity
• You can now run the app and the result should be something like the screens below.

Scroll
down
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 7

Data Persistence and Sharing &


Android Databases
Contents
1. Android intents
2. Persisting data with SharedPreferences
3. Reloading data with SharedPreferences
4. More advanced persistence
5. Databases 101& SQL syntax prime
6. Android SQLite API
7. Coding the database class
8. Coding the DataManager class
9. Running the “SQLiteDatabase” Database app
Weekly Learning Outcomes
1. Explain about using Android intents to switch between
Activity classes and pass data.
2. Design the screen data using the SharedPreferences class &
JavaScript Object Notation.
3. Explain the Android SQLite.
Required Reading
1. Chapter 17 & Chapter 27 (Android Programming for
Beginners 3rd Edition, 2021 by John Horton , Packt
Publishing Ltd.)
Objectives of the chapter
• Different ways to store data in Android device’s permanent storage
• Adding a second Activity class to the app and navigating between the two screens
• Using Android intents to switch between Activity classes and pass data
• Create a simple (very simple) settings screen in a new Activity class
• Persist the settings screen data using the SharedPreferences class.
• Learn about JavaScript Object Notation (JSON) for serialization.
• Implement saving data.
Android Intents
Android intents
• Android apps comprises of multiple Activities.
• *Intent class: class that demonstrates the intent of an Activity class.
• Intent class: enables the user to switch between Activity instances.
• *Activity instances: made from classes with member variables.
• When switching between the multiple screens in an app, the Intents handle variable’s data
value by passing data between Activity instances.
• Intents also enables to interact with other apps too.
• For example, we could provide a link in our app for the user to send an email, make a
phone call, interact with social media, or open a web page in a browser and have the email
app, phone call app, social media app, or web browser do all the work.
Switching Activity
• Consider an app with two Activity based classes. One of the class is FirstActivity class which
will be the starting point of the app. Second activity is the SecondActivity.
• Switching between the two screens: given in the code.
// Declare and initialize a new Intent object called myIntent
Intent myIntent = new Intent(this, SecondActivity.class);
// Switch to the SecondActivity
startActivity(myIntent);
• In code above, we:
• Initializing the Intent object (myIntent).
• Intent has a constructor with two arguments/parameters:
1. The first parameter “this”: is a reference to current activity class (FirstActivity.class)
2. The second parameter is the name of the Activity class we want to open, SecondActivity.class
• *Encapsulation : Hides the information about each other activities → How to share the data?
Passing data between activities
• Intent uses to send/pass a data from one activity to second activity.
• Consider a sign-in screen: user need to pass the user's credentials to each Activity of app
→ Done by using intents.
public class FirstActivity extends AppCompatActivity {
// Create a String called username and set its value to bob 1. We create a String called username
String username = "Bob"; // 1 and set its value to Bob.
2. We used the putExtra method to load
@Override
a string (data) into the intent.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); • We add data using key-value pairs.
setContentView(R.layout.activity_main); • Key: USER_NAME
// Declare and initialize a new Intent object called myIntent • value: username
Intent myIntent = new Intent(this, SecondActivity.class); • Each piece of data needs to be
// Add the username String to the Intent using the accompanied by an identifier
// putExtra method of the Intent class instance that can be used in the
myIntent.putExtra("USER_NAME", username); // 2 retrieving Activity to identify and
// Start the new Activity
retrieve the data.
startActivity(myIntent);
}
}
Passing data between activities
• In SecondActivity, we could then retrieve the string like this:
public class SecondActivity {
// In the receiving Activity, we create the get Intent object
Intent myIntent = getIntent();
// Initialize username with the passed in String
String username = myIntent.getExtras().getString("USER_NAME");
}
• We can retrieve the data using the getExtras method and the appropriate
identifier from the key-value pair.
• key (USER_NAME) must be same which is send by first activity.
• getString() method is for getting the data (key) which is send by first activity.
• The Intent class can help when sending more complex data.
Passing data between activities (Example)
• Create an empty project. Name it Intent.
• Intent project has a class named FirstActivity and layout named activity_first.xml
Passing data between activities (Example)
• Open “activity_first.xml” file and add the following inside of it.
<EditText
android:id="@+id/send_text_id"
android:layout_width="411dp"
android:layout_height="43dp"
android:hint="Input"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.052" />

<Button
android:id="@+id/send_button_id"
android:layout_width="99dp"
android:layout_height="50dp"
android:text="send"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.139" />
Passing data between activities (Example)
• Open the FirstActivity activity file and add the following code inside of it.
public class FirstActivity extends AppCompatActivity {
// Define the variables
Button send_button;
EditText send_text;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
send_button = (Button)findViewById(R.id.send_button_id);
send_text = (EditText)findViewById(R.id.send_text_id);

// add the OnClickListener in sender button


send_button.setOnClickListener(new View.OnClickListener() {
@Override
Passing data between activities (Example)
• Continue code from previous slide.
public void onClick(View v)
{
// get the value which input by user in EditText and convert it to string
String str = send_text.getText().toString();

// Create the Intent object of this class Context() to SecondActivity class


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

// putExtra method put the value in key-value pair


intent.putExtra("message_key", str);
// start the Intent
startActivity(intent);
}
});
}
}
Passing data between activities (Example)
• Now, we have to create a SecondActivity activity file that to receive the data.
• Right click on app folder -> New -> Activity -> Empty Activity
• Keep the default settings, but make sure that Generate a Layout File option is checked.
• Name the layout as activity_second.
• In activity_second.xml, add the following xml code.
<TextView
android:id="@+id/received_value_id"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="Received data"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.005" />
Passing data between activities (Example)
• Open the SecondActivity activity file and add the following code inside of it.
public class SecondActivity extends AppCompatActivity {
TextView receiver_msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
receiver_msg = (TextView)findViewById(R.id.received_value_id);
// In the receiving Activity, we create the get Intent object
Intent myIntent = getIntent();
// receive the value by getString() and getExtras() methods
// key "message_key" must be same which is send by first activity
String str = myIntent.getExtras().getString("message_key");
// display the string into textView
receiver_msg.setText(str);
}
}
Passing data between activities (run the app)
• Run the app. Then, input a data and then click “SEND”.
• The data in the first activity will be send to the second activity.
Persisting data with SharedPreferences
Persisting data with SharedPreferences
• Persist, means that if the user quits the app, then come back to it, their data is still available.
• Three ways to make data persist.
1. A lightweight mechanism known as shared preferences.
2. Traditional file systems.
3. SQLite database system
• SharedPreferences class. is a class that provides access to data that can be accessed and
edited by all Activity classes of an app.
• A SharedPreferences object can be used to store primitive data (for example, integers, strings,
app settings, username, password) in a key/value pair.
• To use SharedPreferences, we need create two objects:
// A SharedPreferences for reading data
SharedPreferences prefs;

// A SharedPreferences.Editor for writing data


SharedPreferences.Editor editor;
Persisting data with SharedPreferences: getSharedPreferences
• As with all objects, we need to initialize them before we can use them.
• We can initialize the prefs object by using the getSharedPreferences method and passing in a
string that will be used to refer to all the data read and written using this object.
• Initialize prefs the using:

prefs = getSharedPreferences("PREFS_FILE_NAME", MODE_PRIVATE);

• PREFS_FILE_NAME: is a string the represent the file name that stores the key/value pairs.
• MODE_PRIVATE: means that any class, in this app only can access the preferences file.
Persisting data with SharedPreferences: Editor
• We then use our newly initialized prefs object to initialize our editor object by calling the edit
method:
editor = prefs.edit();
• We then save the key/value pair using:
editor.putString(“username_key", username_value);
editor.commit();
• putString(“username_key", username_value) is a method uses to save the username and its value.
• Username_key is a label that can be used to refer to the data.
• username_value is the actual data we want to save.
• commit() is a method initiates the saving process.
• If you want to save an integer or boolean data, you can use a respective method:
editor.putInt("age_key", age);
editor.putBoolean("isStudent_key", student);
Reloading data with SharedPreferences
• Let's see how we can reload our data the next time the app is run. The code below will reload
the value that the previous code saved.

String username = prefs.getString("username_key", "new user");


• In the previous code, we load the data from disk using the method appropriate for the data type.
• Username_key is the same label we used to save the data in the first place.
• new user is the default value. If there is no data stored with that label, it will then return the
default value.
SharedPreferences (example)
• Create an empty project. Name it SharedPreferences.
• Open “activity_main.xml” file and add the following XML code inside of it.
<EditText
android:id="@+id/edit_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:hint="Enter your Name"
android:padding="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />

<EditText
android:id="@+id/edit_age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/edit_name"
android:layout_marginStart="12dp"
android:layout_marginTop="8dp"
android:hint="Enter your Age"
android:inputType="number"
android:padding="10dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edit_name" />
SharedPreferences (example)
• Open the MainActivity activity file and add the following code inside of it.

public class MainActivity extends AppCompatActivity {


private EditText name, age;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.edit_name); // get a reference to name widget in layout
age = findViewById(R.id.edit_age); // get a reference to age widget in layout
}
SharedPreferences (example)
• Continue code from previous slide.
// Store the data in the SharedPreference in the onPause() method
// When the user closes the application, onPause() will be called and data will be stored
@Override
protected void onPause() {
super.onPause();

// Creating a shared pref object with a file name "MySharedPref_file" in private mode
SharedPreferences prefs = getSharedPreferences("MySharedPref_file", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();

// write all the data entered by the user in SharedPreference and initiates the saving process
editor.putString("name_key", name.getText().toString());
editor.putInt("age_key", Integer.parseInt(age.getText().toString()));
editor.commit();
}
SharedPreferences (example)
• Continue code from previous slide.
// Fetch the stored data in onResume() when the app opened again
@Override
protected void onResume() {
super.onResume();

// Fetching the stored data from the SharedPreference


SharedPreferences sh = getSharedPreferences("MySharedPref_file", MODE_PRIVATE);

// If there is no data stored in name_key, return the default values ""


// If there is no data stored in age_key, return the default values 0
String s1 = sh.getString("name_key", "");
int a = sh.getInt("age_key", 0);

// Setting the fetched data in the EditTexts in the layout


name.setText(s1);
age.setText(String.valueOf(a));
}
SharedPreferences (example)
• Run the app and observe the following.
1. User enters the data inside of the text fields.
2. If the user closes the app completely, the app is completely destroyed.
3. If the user reopens the application, the data entered previously will be reloaded in the text fields
through the SharedPreferences.

4. Data
1. Enter reloaded
the data again

3. Reopen
the app
2. Close
the app
More advanced persistence
More advanced persistence : JSON
• As the app features advances with more data → required to save and load java
objects including internal data (strings, Booleans and anything else)
• SharedPreferences wasn't designed for save java objects.
• Serialization is uses to save data objects.
• In serialization, the data objects are converted into bits and bytes to store on
the disk.
• De-serialization
• In de-serialization, the store bits and bytes are converted back to data objects
when reloading the app.
• JSON stands for JavaScript Object Notation
• JSON class in Android hide the complexity Serialization process.
• JSON is uses to send data between web applications and servers.
• Widely used in Android
Databases 101 & Android Databases (Chapter 27)
Database
• What is a database?
• A database is place of storage and a means to retrieve, store,
and manipulate data.
• *Internal structure of database varies greatly based on the database.
• What is SQL?
• SQL stands for Structured Query Language.
• SQL is the programming language that is used to manipulate
the data in the database.
• What is SQLite?
• SQLite is Android version of SQL.
• SQLite is a fully functional database management system Database example
(DBMS).
• SQLite uses queries written in SQL.
SQLite example code
• Keywords are similar to JAVA:
• INSERT: Allows us to add data to the database
• DELETE: Allows us to remove data from the database
• SELECT: Allows us to read data from the database
• WHERE: Allows us to specify parts of the database, matching specific
criteria, that we want to use INSERT, DELETE, or SELECT on
• FROM: Used to specify a table or column name in a database
• SQL has types:
• integer: uses for storing whole numbers
• text: uses for storing a simple name or address
• real: uses for storing large floating-point numbers
Operations on database
• Creating a table

• Inserting data into the database


Operations on database
• Retrieving data from the database

• Updating the database structure

score
Android SQLite API
• Two fundamental classes to access the database API in Android:
- SQLiteDatabase class is the class represents the actual database.
- SQLiteDatabase has methods to create, delete, execute SQL commands.
- execSQL method: adding data to the database.
- rawQuery method: getting data from the database.

- SQLiteOpenHelper class is the class responsibly to deal with/manage


database itself and enable to get access to a database and initialize an
instance of SQLiteDatabase
- SQLiteDatabase has to override two methods:
- onCreate method: called the first time a database is used.
- onUpgrade method: called when we upgrade/modify our database using ALERT.
Database cursors
• Besides the classes that give us access to the database and the methods that allow us to
execute our queries, there is the issue of exactly how the results we get back from our queries
are formatted.
• Android Studio has a Cursor class.
• All our database queries will return object of type Cursor class.
Cursor c = dbase.rawQuery(query, null);
• where dbase is object of type SQLiteDatabase and query is the query on database.
• We can use the methods of the Cursor class to selectively access the data of database
returned from the queries, as here:
Log.i(c.getString(1), c.getString(2));
• The previous code would output to logcat the two values stored in the first two columns of the
result that the query returned.
• It is the Cursor object itself that determines which row of our returned data we are currently
reading.
Coding the database class
SQLiteDatabase app - activity_main.xml (example)
• Create an empty project. Name it SQLiteDatabase.
• Open “activity_main.xml” file and add the following xml code inside of it.
<EditText
android:id="@+id/editName"
android:layout_width="255dp"
android:layout_height="45dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:hint="Type a name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.102"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.023" />

<EditText
android:id="@+id/editAge"
android:layout_width="255dp"
android:layout_height="42dp"
android:layout_below="@+id/editName"
android:layout_alignStart="@+id/editName"
android:layout_alignLeft="@+id/editName"
android:hint="Type their age"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.102"
app:layout_constraintStart_toStartOf="parent"
SQLiteDatabase app - DataManager.java (example)
• Creating a new class and name it DataManager.java.
• Open “DataManager.java” class and add the following code inside of it.
public class DataManager {
// We create a variable to represents the actual database.
private SQLiteDatabase dbase;
// We create variables for id, name and age table's columns.
public static final String TABLE_COLUMN_ID = "_id";
public static final String TABLE_COLUMN_NAME = "name";
public static final String TABLE_COLUMN_AGE = "age";

// We create variables for: Database name, database version and table name.
private static final String DB_NAME = "my_db";
private static final int DB_VERSION = 1;
private static final String TABLE_N_AND_A = "names_and_age";
// We add the constructor that will create an instance of SQLiteOpenHelper.
// The constructor also initializes the db member, which is our SQLiteDatabase reference.
public DataManager(Context context) {

// Create an instance of our internal myDbHelper class


myDbHelper helper = new myDbHelper(context);
// We get a reference/create a variable to a SQLiteDatabase object,
// using SQLiteOpenHelper’s getWritableDatabase() method
// as we are writing data in our database.
dbase = helper.getWritableDatabase();
}
SQLiteDatabase app - DataManager.java (example)
• Continue code from previous slide.
// create a Database Helper class whose only function is to provide for
// the creation, modification, and deletion of tables in the database.
// The primary function of the class is to determine what must be done on
// creation of the database and what must be done when the database is upgraded.

// A Context is a handle to the system; it provides services like resolving resources,


// obtaining access to databases and preferences, and so on.
private class myDbHelper extends SQLiteOpenHelper {

public myDbHelper(Context context) {


super(context, DB_NAME, null, DB_VERSION);
}
// This method only runs the first time the database is created.
// The onCreate method is for creating a database by running a sqlite query
@Override
public void onCreate(SQLiteDatabase dbase) {
// Create a table for data and all their details
// On below line we are creating an sqlite query and we are
// setting our column names along with their data types.
String query = "create table " + TABLE_N_AND_A + " ("
+ TABLE_COLUMN_ID + " integer primary key autoincrement not null,"
+ TABLE_COLUMN_NAME + " text not null,"
+ TABLE_COLUMN_AGE + " text not null);";
// Here, we call execSQL method to execute above sql query
dbase.execSQL(query);
}
SQLiteDatabase app - DataManager.java (example)
• Continue code from previous slide.
@Override
public void onUpgrade(SQLiteDatabase dbase, int oldVersion, int newVersion) {
// The onUpgrade method is left intentionally blank for this app.
}
}

// Insert a record into the database table


// When adding/deleting data to the database, we will use execSQL, and
// when getting data from the database, we will use the rawQuery method
public void insert(String name, String age){
// Add all the details to the table
String query = "INSERT INTO " + TABLE_N_AND_A
+ " (" + TABLE_COLUMN_NAME + ", " + TABLE_COLUMN_AGE + ") "
+ "VALUES "
+ "(" + "'" + name + "'" + ", " + "'" + age + "'" + "); ";
Log.i("insert() = ", query);
dbase.execSQL(query);
}

// Delete a record from the database table


public void delete(String name){
// Delete the details from the table if already exists
String query = "DELETE FROM " + TABLE_N_AND_A +
" WHERE " + TABLE_COLUMN_NAME + " = '" + name + "';";
Log.i("delete() = ", query);
dbase.execSQL(query);
}
SQLiteDatabase app - DataManager.java (example)
• Continue code from previous slide.
// Get all the records from the database table
public Cursor selectAll() {
Cursor c = dbase.rawQuery("SELECT *" +" from " + TABLE_N_AND_A, null);
return c;
}

// Find a specific record


public Cursor searchName(String name) {
String query = "SELECT " + TABLE_COLUMN_ID + ", "
+ TABLE_COLUMN_NAME + ", "
+ TABLE_COLUMN_AGE +
" from " + TABLE_N_AND_A +
" WHERE " + TABLE_COLUMN_NAME + " = '" + name + "';";

Log.i("searchName() = ", query);


Cursor c = dbase.rawQuery(query, null);
return c;
}

// Output the cursor contents to the logcat


public void showData(Cursor c){
// moveToNext method move Cursor to the next row that is ready for reading:
while (c.moveToNext()){
Log.i(c.getString(1), c.getString(2));
}
}
}
SQLiteDatabase app - MainActivity.java (example)
• Open “MainActivity.java” class and add the following code inside of it.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

// Variable names (references) for all buttons and EditText in activity_main.xml layout
Button btnInsert;
Button btnDelete;
Button btnSelect;
Button btnSearch;
EditText editName;
EditText editAge;
EditText editDelete;
EditText editSearch;

// This is our DataManager instance


DataManager dm;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dm = new DataManager(this);

// get a reference to the UI items/widgets/elements


btnInsert = (Button) findViewById(R.id.btnInsert);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnSelect = (Button) findViewById(R.id.btnSelect);
btnSearch = (Button) findViewById(R.id.btnSearch);
SQLiteDatabase app - MainActivity.java (example)
• Continue code from previous slide.
EditText editName = (EditText) findViewById(R.id.editName);
EditText editAge = (EditText) findViewById(R.id.editAge);
EditText editDelete = (EditText) findViewById(R.id.editDelete);
EditText editSearch = (EditText) findViewById(R.id.editSearch);

// Register/link MainActivity Button items with a listener.


// When the button clicked, onClick method will be called.

btnSelect.setOnClickListener(this);
btnInsert.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnSearch.setOnClickListener(this);
}
SQLiteDatabase app - MainActivity.java (example)
• Continue code from previous slide.
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.btnInsert:
dm.insert(editName.getText().toString(), editAge.getText().toString());
Toast.makeText(this,"Data Inserted", Toast.LENGTH_LONG).show();
break;

case R.id.btnDelete:
dm.delete(editDelete.getText().toString());
Toast.makeText(this,"Data Deleted",Toast.LENGTH_LONG).show();
break;

case R.id.btnSearch:
dm.showData(dm.searchName(editSearch.getText().toString()));
break;

case R.id.btnSelect:
dm.showData(dm.selectAll());
break;
}
}
}
Running the SQLite Database app
• Run the app and add the names and ages to the database using the Insert button.

• Verify the execution is successful of data added by clicking “SELECT *” button and checking the
logcat window.
Running the SQLite Database app
• Enter a name to delete and click the DELETE button. Analyse the
output by clicking “SELECT *” button and checking the logcat window.

• Enter a name to search for and click the SEARCH button. Analyse the
output by checking the logcat window.
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 9

Why React and Why React Native


Contents
1. What is React?
2. React Features
3. What's new in React?
4. What is React Native?
5. React and JSX are familiar
6. The mobile browser experience
7. Android and iOS – different yet the same
8. The case for mobile web apps
Weekly Learning Outcomes

1. Describe the advantages of React


2. Explain how Does React Native Work?
Required Reading
1. Chapter 1 and Chapter 13 (React and React Native: A
complete hands-on guide to modern web and mobile
development with React.js,3rd Edition, 2020, Adam
Boduch, Roy Derks)

Recommended Reading
React: https:/ / facebook. github. io/ react
What is React?
What is React?
• React is "A JavaScript library for building user interfaces."
• It is a library for building user interfaces (UIs) for web and mobile
apps.
• It is view layer in an application.
• *It is similar to jQuery manipulates UI elements OR Handlebars
templates are inserted into the page.
• The following diagram illustrates where React fits in our frontend code:
• The Document Object Model (DOM) is a way to represent HTML in
the browser
• React component is the building block of a React application.
• *React components change what the user sees.
DOM/ UI Tree
• *Handles the job of getting HTML into the page to render data to UI.
• *Rendering technology
• *Simplifies the application development
Components of React
• React is divided into two major APIs: React component API & React DOM
• React component: Parts of the page that are rendered by React DOM
• Data: data that comes from somewhere and is rendered by the component.
• Life Cycle: Consists of methods that respond to components entering and exiting phase
• Events: the code that we write for responding to user interactions.
• JSX: syntax of React components used to describe UI structures.
• React DOM: This is the API that has methods to perform the actually rendering on a web
page.
Declarative UI structures
• Syntax used by React components is called JSX (JavaScript XML).
• JSX is central to React components.
• JSX is an extension to javascript where you will have the power of using
HTML/XML and Javascript together.
• Here is a simple example of a JSX code.
const h1tag = "<h1> Hello, from JSX Tutorials! </h1>";
• JSX uses declarative programming approach – *Need not perform little micro-
operations to change the content of a component.
• In declarative programming approach, we declare what is the results we want and leave the
programming languages to figure out how to produce them.
• JSX NOT uses Imperative programming:
• In imperative programming approach, we have to write a sequence of instructions to tell the
programming languages what to do.
• Issue in UI development.
*Declarative UI structures
• The JSX itself is usually HTML markup, mixed with custom tags for React
components.
• React components don't require executing steps in an imperative way.
• The XML-style syntax makes it easy to describe the structure of the UI.
• Called declarative programming and is very well suited for UI development.
• Once the UI structure is declared – specification of changes has to be given.
*Time and data
• React components rely on data being passed into them.
• This data represents the dynamic parts of the UI.
• For example, a UI element that's rendered based on a Boolean value could change the next time
the component is rendered. Here's a diagram of the idea:
• Each time the React component is rendered, it's like taking a snapshot of the JSX at that exact
moment in time.
• As the application moves forward through time, an ordered
collection of rendered UI components will be obtained.
• In addition to declaratively describing what a UI should be,
re-rendering the same JSX content makes things much
easier for developers.
• The challenge is making sure that React can handle the
performance demands of this approach.
*Performance matters
• Using React to build UIs means that we can declare the structure of the UI with JSX.
• Less error-prone than the imperative approach of assembling the UI piece by piece.
• Declarative approach does present a challenge: performance.
• For example, having a declarative UI structure is fine for the initial rendering, because
there's nothing on the page yet. So, the React renderer can look at the structure declared
in JSX and render it in the DOM browser.
• The Document Object Model (DOM) represents HTML in the browser after it has been
rendered. The DOM API is how JavaScript is able to change content on the page.
*Performance matters
• On the initial render, React components and their JSX are no different from other
template libraries.
• For instance, Handlebars will render a template to HTML markup as a string, which is
then inserted into the browser DOM.
• Where React is different from libraries such as Handlebars is when data changes, the
components has to be re-rendered.
• Handlebars will just rebuild the entire HTML string, the same way it did on the initial
render. Since this is problematic for performance, implementing imperative workarounds
leads to manually update tiny bits of the DOM.
• Causes a tangled mess of declarative templates and imperative code to handle the
dynamic aspects of the UI.
• This does not occur in React which differentiates React from other libraries.
• Components are declarative for the initial render, and they stay this way even as they're
re-rendered. It's what React does under the hood that makes re-rendering declarative UI
structures possible.
Virtual DOM
• The Document Object Model (DOM) allows JavaScript to read and manipulate the content of a
document (in this case, an HTML document).
• A simple way to think of the DOM is in terms of the document tree

• React has something called the virtual DOM, which is used to keep a representation of the real
DOM elements in memory.
*Virtual DOM
• It does this so that each time we re-render a component, it can compare the new content to the
content that's already displayed on the page.
• Based on the difference, the virtual DOM can execute the imperative steps necessary to make the
changes. So, not only do we get to keep our declarative code when we need to update the UI, but
React will also make sure that it's done in a performant/efficient way.
• Here's what this process looks like:
• Like any other JavaScript library, React is constrained by
the run-to-completion nature of the main thread.
• For example, if the React internals are busy diffing content
and patching the DOM, the browser can't respond to user
input
• React should be flexible enough to adapt to different
platforms where the app would be deployed in future.
*The Right level of abstraction
• React code is abstraction.
• Abstraction means don't necessarily care what the render target is.
• *JSX syntax translates to low-level operations that update the UI.
• *The render target happens to be the browser DOM with React, but it isn't restricted to
the browser DOM.
• *It is not mandatory to know the target for react to translate the declarative UI
Components
• React has the potential to be used for any UI to create, on any conceivable device.
• *The abstraction level with React is at the right level, and it's in the right place.
React targeting more than just the browser:
• The following diagram gives you an idea of how React can target more than just the
browser:

• From left to right, we have React Web (just plain React), React Native, React Desktop,
and React Toast. Same pattern is applied to target something new:
➢ Implement components specific to the target.
➢ Implement a React renderer that can perform the platform-specific operations under the
hood.
• React knowledge can be used to focus on describing the structure of the UI on any
platform.
React Features
React Features
The features of React 16 include the following:
1. Revamped core architecture
2. Lifecycle methods
3. Context API
4. Rendering fragments
5. Portals
6. Rendering lists and strings
7. Handling errors
8. Server-side rendering
Revamped core architecture
• Biggest change in React 16 - change made to the internal reconciliation code.
• *These changes don't impact the way that you interact with the React API.
• *These changes were made to address some pain points that were preventing
React from scaling up in certain situations.
• For example, one of the main concepts of this new architecture is that of fibers.
• React Fiber is a complete, backwards compatible rewrite of the React core.
• The goal of React Fiber is to increase its suitability for areas like animation.
• **Instead of rendering every component on the page in a run-to compilation way,
React renders fibers—smaller chunks of the page that can be prioritized and
rendered asynchronously.
Lifecycle methods
• React 16 had to renovation some of the lifecycle methods that are available to
class components.
• Some lifecycle methods are deprecated and will eventually be removed
because they will be problematic for future async rendering functionality in
React.
• **For example, a common way to initialize state in a React component is to use
the componentWillMount() lifecycle method. Once this method is removed from
React, the initial state directly can be set as an instance value.
The Context API
• React has provided an experimental Context API for developers.
• Context is an alternative approach to passing data from one component to the next.
• *For example, using properties, data can be passed through a tree of
components that is several layers deep.
• *The components in the middle of this tree don't actually use any of these
properties—they're just acting as intermediaries.
• **This becomes problematic as your application grows more properties in the source add to
the complexity.
Rendering fragments
• React component renders several sibling elements,
• Eg: Three <p> elements: have to wrap them in <div>
• *React would only allow components to return a single element.
• *The only problem with this approach - leads to a lot of unnecessary DOM
structure; <div> elements.
• Wrapping your elements with <Fragment> is the same as wrapping them with
<div>, except there won't be any extra DOM elements.
Portals
• React portal provides a way to render an element outside of its component
hierarchy (DOM tree), i.e., in a separate component.
• *When a React component returns content, it gets rendered into its parent
component.
• *Then, that parent's content gets rendered into its parent component and so on,
all the way to the tree root.
• *Render something that specifically targets a DOM element.
• *For example, a component that should be rendered as a dialog probably doesn't
need to be mounted at the parent.
• *Using a portal can control precisely where the component's content is rendered.

• Rendering lists and strings: Similar to returning string value. Can just
return a list of strings or a list of elements.
Handling errors
• A JavaScript error in a part of the UI break the whole app.
• To solve this problem for React users, React 16 introduces a new concept of an
“error boundary”.
• Error boundaries are React components that catch JavaScript errors anywhere in
their child component tree, log those errors, and display a fallback UI instead of
the component tree that crashed.
• *Where exactly to handle errors?
• *Error boundaries: created by implementing the componentDidCatch() lifecycle
method in a component.
• *Serve as the error boundary by wrapping other components.
• *If any of the wrapped components throw an exception, the error boundary
component can render alternative content.
Server-side rendering (SSR)
• In React, Server-side rendering is where the server returns a ready to render
HTML page and JavaScripts required to make the page interactive.
• *The html is rendered immediately with all the static elements.
• *Popular technique for rendering a client-side single page application (spa) on
the server.
• Then send a fully rendered page to the client.
• *Allows for dynamic components to be served as static html markup.
What's new functions in React?
What's new functions in React?
• Memoizing functional components.
• Code splitting and loading.
• Hooks.
Memoizing functional components
• Using react.Memo() function, memoized components avoid re-rendering a
components if the component data hasn't changed by using Virtual DOM.
• *The react.Memo() function is the modern equivalent of the purecomponent
class.
• *react.Memo() function automatically handle checking whether the component
data has changed or not and whether or not the component should re-render.
• *The challenge with this approach is that it is now common for large react
applications to have a lot of functional components.
• *Can pass functional components to react.Memo() and they'll behave like
purecomponent.
Code splitting and loading
• Code splitting: reduces the size of the code bundles that are sent to the
browser, which can dramatically improve the user experience.
• Provides a huge efficiency gain.
• Done by react.Lazy() function; prefetching the components,
• *Code splitting and the user experience of waiting for pieces of the
application to load are integral parts of the application.
• *By combining react.Lazy() and the suspense component, fine-grained
control over the app is split up is achieved.
Hooks
• Hooks are functions that extend the behavior of functional React components.
• Instead of relying on classes to build components, you can use the React Hooks
API.
• *Hooks are used to "hook into" the React component machinery from your React
components.
• *React Hooks API: pass functions to build components that have state or that rely
on executing side effects when the component is mounted.
What is React Native?
Chapter 13
What is React Native?
• React Native is a JavaScript framework for writing real, natively rendering mobile applications for
iOS and Android. It’s based on React
• In React Native, instead of targeting the browser, it targets mobile platforms.
• React Native is like React, but it uses native components instead of web components as building
blocks.
• React Native uses a technique that makes asynchronous calls to the underlying mobile OS,
which calls the native widget APIs (TextView, ScrollView…etc).
• *There's a JavaScript engine, and the React API is mostly the same as React for the web.
• *The difference is with the target; instead of a DOM, there are asynchronous API calls.
• The concept is visualized here:
• *React Native ships with components
implemented for mobile platforms, instead of
components that are HTML elements.
• The same React library that's used on the web is
used by React Native and runs in JavaScriptCore.
• Messages that are sent to native platform APIs are
asynchronous and batched for performance
purposes.
React and JSX are familiar
React and JSX are familiar
• React and JSX are good at declaring UI components
• What attracts React developers to be React Native developers?
1. Huge demand for mobile apps→ *mobile web browser is not that convenient as
the native app experience.
2. JSX is a fantastic tool for building UIs.
• Rather than having to learn new technology, it's much easier to use what you know.
3. React is valuable from a development-resource perspective.
• Instead of having a team that does web UIs, a team that does iOS, a team that does Android,
and so on, there's just the UI team that understands React.
The mobile browser experience
• What makes developing UIs for mobile browsers difficult using react?
• Mobile browsers lack many capabilities of mobile applications *since browsers cannot
replicate the same native platform widgets as HTML elements.
• Native widget requires less maintenance.
• Using widgets that are native to the platform → *consistent with the rest of the platform.
• *For example: A date picker in an application looks different from all the date pickers the user
interacts with on their phone.
• Familiarity is key. using native platform widgets makes familiarity possible.
• User interactions on mobile devices are fundamentally different from the interactions on
the web application;
• i.e. web applications assume presence of mouse.
• React native is a much better candidate for handling gestures than react for the web.
• React native use actual components from the platform. *components of the app remain
updated when the mobile platform is updated.
• *Consistency and familiarity are key factors for good user experience.
Android and iOS – different yet the same
Android and iOS – different yet the same
• There are several areas that overlap between iOS and Android where the differences are trivial.
• The two widgets aim to accomplish the same thing for the user, in roughly the same way.
• React Native will handle the difference and provide a unified component.
• *React Native is not cross platform solution that will run a single React application natively on
any device.
• *React Native enables web developers to create robust mobile applications using their existing
JavaScript knowledge
• *iOS and Android are different on many fundamental levels. Even their user experience
philosophies are different, so trying to write a single app that runs on both platforms is
categorically misguided.
• Goal of React Native:
✓ Enables the app to take advantage of an iOS specific widget or an Android-specific widget.
✓ Provide a better user experience for that particular platform
✓ *Trump the portability of a component library.
*The case for mobile web apps
• Not every will be willing to install an app → Due to download count and
rating.
• The barrier to entry is much lower with web applications—the user only
needs a browser.
• Cannot replicate everything that native platform UIs can offer.
• A good web UI is the first step toward getting download counts and
ratings up for the mobile app.
• Goal of a good mobile app:
• Standard web (laptop/desktop browsers)
• Mobile web (phone/tablet browsers)
• Mobile apps (phone-/tablet-native platform)
• High demand for your mobile app compared to the web versions
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 10

Rendering with JSX


Contents
1.Your first JSX content
2.Rendering HTML
3.Describing UI structures
4.Creating your own JSX elements
5.Using JavaScript expressions
6.Fragments of JSX
Weekly Learning Outcomes

1. Explain the basics of JSX, including its declarative structure,


which leads to more maintainable code
2. Explain the Fragments of JSX
Required Reading
1. Chapter 2 (React and React Native: A complete hands-on guide
to modern web and mobile development with React.js,3rd
Edition, 2020, Adam Boduch, Roy Derks)

Recommended Reading
Introducing JSX: https:/ / reactjs. org/ docs/ introducing- jsx. Html

Fragments: https:/ / reactjs. org/ docs/ fragments. html


First JSX content
First JSX content
React tool: codesandbox
• Here's your first JSX application:

Hello, JSX

1: import React component from ‘react’ package.


2: import render method/function from react-dom package.
3: Render function is used to return the JSX which you want to display in a component (webpage).
• The purpose of the function is to display the specified JSX code inside the specified DOM element of
HTML which has the id=root.
• The render() function takes JSX (HTML markup)” as the first argument and renders it to the DOM node
passed as the second argument.
• -The actual JSX content in this example renders a paragraph with some bold text inside; Hello, JSX.
• -Remember: The JSX itself is usually HTML markup, mixed with custom tags for React components.
• -document.getElementById('root’): Render the whole React app into the DOM element with id=root.
• -The render() function tells React to take your JSX markup and transform it into JavaScript statements
that update the UI in the most efficient way possible.
• -React has unique conventions that should be followed when using HTML tags.
Rendering HTML
Rendering HTML
• At the end of the day, the job of a React component
is to render HTML into the DOM browser.
• JSX has support for HTML tags.
• Any HTML tag can be rendered in JSX to get the
expected output.
• *When rendering JSX, element tags reference React
components.
• *React comes with HTML components.
• *<div> tag is surrounded by a group of all the other
tags as its children→ React needs a root component
to render.
• *HTML elements rendered using JSX closely follow
regular HTML element syntax with a few subtle
differences regarding case sensitivity and attributes.
HTML tag conventions
• Tag names are case sensitive and non-HTML elements are capitalized.
• Here's an example that illustrates these ideas:
• This example will fail to compile because React doesn't know about the <Button> element; it only knows about <button>.
• Any valid HTML tags can be used as JSX tags.
• HTML tags can be used to describe the structure of your page content.
• *Easy to scan the markup and spot the built-in HTML elements.
• *Can also pass HTML elements any of their standard properties, a warning about the unknown
property is logged.
Describing UI structures
Describing UI structures
• JSX is capable of
describing screen
elements in a way that
ties them together to
form a complete UI
structure.
• Let's look at some JSX
markup that declares a
more elaborate structure
than a single paragraph:
→Describing UI structures
• This JSX markup describes some fairly sophisticated UI structure. Yet, it's easier to read
than imperative code because it's XML, and XML is good for concisely expressing a
hierarchical structure. This is how we want to think of our UI when it needs to change, not
as an individual element or property.
• There are a lot of semantic elements in this markup describing the structure of the UI.
• For example, the <header> element describes the top part of the page where the title is, and the <main>
element describes where the main page content goes.
• This type of complex structure makes it clearer for developers to reason about. But before
we start implementing dynamic JSX markup, let's create some of our own JSX
components.
Creating your own JSX components
Creating your own React/JSX components
• React class components have
a render() method. This method
should return some React elements
created with JSX.
• -Components are the fundamental
building blocks of React.
• -Components are the vocabulary of
JSX markup.
• -Create new JSX elements to
encapsulate larger structures.
• -Custom tag can be used.
• -The React component returns the
JSX that goes where the tag is used.
• -The component encapsulate HTML
elements.
• -Let's look at the following example:
→ Creating your own React/JSX components
• This is the first React component.
• Create new React/JSX components → by creating a class called MyComponent, which extends
the Component class from React.
• Rendering a <MyComponent> component.
• The HTML that this component encapsulates is returned by the render() method.
• In this case, when the JSX <MyComponent> is rendered by react-dom, it's replaced by a
<section> element, and everything within it.
• In the preceding example, the MyComponent class was declared in the same scope as the call to
render(), so everything worked as expected.
• Import components, adding them to the appropriate scope.
• HTML elements such as <div> often take nested child elements.
Nested elements

• Importing two of own React components: MySection and


MyButton.
• In this example, the button text: “My Button Text” is a child
of MyButton component, which is, in turn, a child of
MySection component.
• <Component>text</Component>
• What you put between the tags will be passed to
component as props.children.
→ Nested elements
• JSX markup is useful for describing UI structures that have parent-child relationships.
• Child elements are created by nesting them within another component: the parent.
• For example, a <li> tag is only useful as the child of a <ul> tag or a <ol> tag
• Can make similar nested structures with your own React components.
• Use the children property.
• Here's the JSX markup:
→ Nested elements
• Importing two of own React components: MySection and MyButton.
• <MyButton> is a child of <MySection>.
• The MyButton component accepts text as its child, instead of more JSX elements.
→ Nested elements
• This component renders a standard <section> HTML element, a heading, and then
{this.props.children}. It's this last piece that allows components to access nested elements or text,
and to render them.
• The two braces used in the preceding example are used for JavaScript expressions.
• More details of the JavaScript expression syntax found in JSX markup in the following section.
• Look at the MyButton component:
→ Nested elements
• This component uses the exact same pattern as MySection; take the {this.props.children} value and
surround it with markup. React handles the details.
• In this example, the button text is a child of MyButton, which is, in turn, a child of MySection.
• However, the button text is transparently passed through MySection.
• Not required to write any code in MySection to make sure that MyButton got its text .
• Here's what the rendered output looks like:

• Components can be organized by placing them within a namespace.


Using JavaScript expressions
Using JavaScript expressions in JSX
• JavaScript expression syntax looks like in JSX markup:
• Anything that is a valid JavaScript expression, including nested JSX, can go in between
the braces: { }.
• For properties and text, this is often a variable name or object property.
• In this example, the !enabled expression computes a Boolean value.
• Rendered output looks like:
→ Using JavaScript expressions in JSX
• JSX has a special syntax that allows you to embed JavaScript expressions.
• Any time React renders JSX content, expressions in the markup are evaluated.
• This is the dynamic aspect of JSX,
• How to use expressions to set property values and element text content.
• How to map collections of data to JSX elements.

→ Dynamic property values and text


• Some HTML property or text values are static→ don't change as JSX markup is re-
rendered.
• Other values, the values of properties or text, are based on data that is found
elsewhere in the application. Remember, React is just the view layer.
Mapping collections to elements
• The best way to dynamically control JSX elements is to map them from a collection
(Arrays, Objects). Let's look at an example of how this is done:

• The map() function lets


you manipulate the items
in an array/object by
iterating and accessing
individual items.
• To use the map() function,
attach it to an array/object
you want to iterate over.
→ Mapping collections to elements
• The first collection is an array called array, populated with string values.
• Moving down to the JSX markup, you can see the call to array.map(), which returns
a new array.
• The mapping function is actually returning a JSX element (<li>), meaning that each item in the
array is now represented in the markup.
• The result of evaluating this expression is an array
• The object collection uses the same technique→call Object.keys() and then map
this array.
• Can control the structure of React components based on the collected data.
• No need to rely on imperative logic to control the UI.
→ Mapping collections to elements
• Here's what the rendered output looks like:
• JavaScript expressions bring JSX content to life.
• React evaluates expressions and updates the HTML content
based on what has already been rendered and what has
changed.
• Understanding how to utilize these expressions is important
because they're one of the most common day-to-day
activities of any React developer
Fragments of JSX
Fragments of JSX
• Fragments are a way to group together chunks of markup (children) without having to
add unnecessary structure to your page (extra node to DOM tree).

<div> does nothing but add use fragments to avoid


another level of structure unnecessary tags; <div>.
→ Fragments of JSX
• React 16 introduces the concept of JSX fragments.
• Fragments are a way to group together chunks of markup (children)
without having to add unnecessary structure to your page (extra node to
DOM tree).
• For example, a common approach is to have a react component return
content wrapped in a <div> element.
• This element serves no real purpose and adds clutter to the DOM.
• Two versions of a component:
• One uses a wrapper element
• Uses the new fragment feature
→ Fragments of JSX

• The two elements rendered are <WithoutFragments> and


<WithFragments>. Here's what they look like when rendered:

• Let's compare the two approaches now.


→ WithoutFragments: Using wrapper elements
• The first approach is to wrap sibling elements in <div>. Here's what the
source looks like:
→ WithoutFragments: Using wrapper elements
• The essence of this component is the <h1> and <p> tags.
• to return them from render() → wrap them with <div>.
• inspecting the DOM using browser dev tools reveals that <div> add
another level of structure:
→ WithFragments: Using fragments
• Now, let's take a look at the With Fragments component, where we have
avoided using unnecessary tags:
→ WithFragments: Using fragments
• Instead of wrapping the component content in <div>, the <Fragment> element is
used.
• This is a special type of element that indicates that only its children need to be
rendered.
• With the advent of fragments in JSX markup→less HTML rendered on the page
• No need to use tags such as <div> for the sole purpose of grouping elements
together.
• when a component renders a fragment, React knows to render the event's child
element wherever the component is used.
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 11

Component Properties and State


Contents
1. What is component state?
2. What are component properties?
3. Setting a component state
4. Passing property values
5. Stateless components
Weekly Learning Outcomes

1. Explain the state and properties in React components


2. Describe the concept of a container component
Required Reading
1.Chapter 3 (React and React Native: A complete hands-on guide
to modern web and mobile development with React.js,3rd
Edition, 2020, Adam Boduch, Roy Derks)
Recommended Reading
1. Instance Properties: https:/ / reactjs. org/ docs/ react- component. Html # instance-
properties- 1
2. Setting the Initial State: https:/ / reactjs. org/ docs/ react- without- es6.
html#setting- the- initial- state
3. Context: https:/ / reactjs. org/ docs/ context. Html
4. Spread syntax: https:/ / developer. mozilla. org/ en- US/ docs/ Web/ JavaScript/
Reference/ Operators/ Spread_ syntax
What is component state?
What is component state?
• *React components declare the structure of UI elements using JSX.
• *Components need data to be useful.
• *For example, a component JSX declare <ul> that maps a JavaScript collection to <li>
elements.
• State is the dynamic part of a React component. It declares the initial state of a component,
which changes over time.
• Ex: rendering a component where a piece of its state is initialized to an empty array.
• Later on, this array is updated with data using setState(). This is called a change in state,
• Whenever a React component needs to change its state, the component will automatically re-
render itself by calling render().
• *The state of a component is something that either the component itself can set, or other pieces
of code, outside of the component.
• The process is visualized here:
Creating and Setting a component state
Creating and setting a component state

• The JSX of this component depends on two state values: heading and content.
• The component is first rendered with its default state.
• setTimeout method is uses to execute a function or block of code after a period of time.
• The setTimeout() called after 3 seconds. It uses setState() to change the two state property values. This change
will be reflected in the UI.
→ Setting a component state
• React code that sets the state of components.
• The initial state—that is, the default state of a component.
• How to change the state of a component → causing it to re-render itself.
• How to merge a new state with an existing state.?

→ Setting an initial component state


• The initial state of a component not explicitly set.
• The initial state of a component will always be an object with one or more properties.
• For example, a component that uses a single array as its state : the initial array is set as a
property of the state object.
• Every React component uses a plain object as its state.
→ Creating a component state
• Render a component with initial state and update its state. This means that the component
will be rendered twice.
• Component:
→ Creating a component state
• The JSX of this component depends on two state values—heading and content.
• The component also sets the initial values of these two state values, which means that it
can be rendered without any unexpected "gotchas."
• Code that renders the component and then re-renders it by changing the state:
→ Creating a component state
• The component is first rendered with its default state.
• Spot in this code is the setTimeout() call. After 3 seconds, it uses setState() to change the
two state property values. This change will be reflected in the UI.
• The initial state when rendered:

• The rendered output after the change of state:


What are component properties?
What are component properties?
• Properties are used to pass data into your React components.
• In the context of JSX, properties are called attributes, *probably
because that's what they're called in XML parlance.
• .Instead of calling a method with a new state as the argument,
properties are passed only when the component is rendered. That
is, you pass property values to JSX elements.
• .Properties are different than state because they don't change after
the initial render of the component.
• .If a property value has changed, to re-render the initial
component, then re-render the JSX that was used to render it in
the first place.
• .The React internals take care of making sure this is done
efficiently.
• .Different than a stateful component. The real difference is that with
properties, it's often a parent component that decides when to
render the JSX.
• .The component doesn't actually cannot re-render itself.
• .Here's a diagram of rendering and re-rendering a component
using properties:
Passing property values
Passing property values
• Properties are like state data that gets passed into components.
• Properties are different from state in that they're only set once, which is when the
component is rendered.
• Default property values are set as a class attribute called defaultProps.
• Let's take a look at a component that declares default property values:
• In this example, the MyButton component renders a <button> element using the default disabled and text
property values.
Stateless/ function components
Stateless components
• The components you've seen so far is classes components that extend the base
Component class.
• It's time to learn about functional components in React
• There's zero difference between the class-based and function-based React
components, from a JSX point of view.
• The JSX looks exactly the same whether the component was declared using the
class or function syntax.
Pure functional components
• A functional React component is just what its name suggests—a function
• render() method is a functional component.
• The job of a functional React component is to return JSX, just like a class based
React component.
• functional components has no state and no lifecycle methods.
• Functional components are lightweight; they don't have any state or lifecycle.
• Why would you want to use functional components?
• It's a matter of simplicity more than anything else. If your component renders
some JSX and does nothing else, then why bother with a class when a function
is simpler?
• A pure function is a function without side effects.
• Functions that always return the same value with a given argument values are
easier to test as well.
Functional components

// MyFunction.js

• Create a Function component called my_func


• Now your React application has a component called my_func, which returns an <h1> element.
• To be able to use a component later, you need to first export it.
• To use this component in your application, use similar syntax as normal HTML:
<MyFunction />
Functional components/ passing values

• This function is accepting a single “props” (which stands for properties) object argument
with data and returns a React element.
• When React sees an element representing a user-defined component, it passes JSX
attributes and children to this component as a single object. We call this object “props”.
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 13

Kick-Starting React Native Projects and


Building Responsive Layouts with Flexbox
Contents
1.Installing and using the Expo command-line tool
2.Viewing your app on your phone
3.Viewing your app on Expo Snack
4.Flexbox is the new layout standard
5.Introducing React Native styles
6.Building Flexbox layouts
Weekly Learning Outcomes
1. Explain how to kick-start a React Native project using the
Expo command-line tool
2. Explain how to use the Flexbox model to lay out our React
Native screens
Required Reading
1. Chapter 14 and Chapter 15 (React and React Native: A
complete hands-on guide to modern web and mobile
development with React.js,3rd Edition, 2020, Adam
Boduch, Roy Derks)

Recommended Reading
Layout with Flexbox: https:/ / facebook. github. io/ react- native/ docs/
Flexbox
Installing and using the Expo command-line tool
Installing and using the Expo command-line tool
• The Expo command-line tool is the preferred way start React Native project.
• Handles the creation of the project framework that is required to run a basic React
Native application.
• Installing the Expo command-line tool:
1. Type in the following command prompt:
npm install -g expo-cli
2. Once the installation is complete, new expo command will be available on the
system.
3. To start a new project, run the expo init command, as follows:
expo init my-project
Installing and using the Expo command-line tool
4. The following details appear on the terminal to enter the details of the project:

• The default selection is “blank Managed workflow” .


• This enables to use the Expo tools and services during the development of the
application compatible on different mobile devices.
Installing and using the Expo command-line tool
5. The project configuration is updated accordingly completing the Expo project
creation process.

• Now, a blank React Native project is created,


• Next → how to launch the Expo development server on the system and view the
app on one of the mobile devices.
Viewing your app on your phone
Viewing your app on your phone
• In order to view your React Native project on your
device during development, we need to start the
Expo development server:
1. In the command-line terminal, enter in the project
directory:
cd path_to_my-project
i.e. cd my-project
2. Run the following command to start the
development server:
npm start
3. Some information about the developer server is
displayed on the terminal:
.Viewing your app on your phone
4. You can open/view the app in the browser
tab with a UI for managing where the
application is run, viewing logs, and other
miscellaneous activities by copy and paste
the following URL in web browser:
http://localhost:19002
• Here is what the Expo app looks like:
• The logs of the process that bundles the React
Native code and send it to an emulator is
displayed on the right side of the screen.
• A QR code that you can scan with the camera
on the device appears on the bottom left side.
Viewing your app on your phone
5. In order to view our app on our devices, we need to
install the Expo app. You can find it in the Play
Store app on Android devices or in the App Store on
iOS devices.
• Once you have Expo app installed, you can click on the Scan
QR Code button:Then click on the Scan QR Code button:
• This will open the camera app on the device.
.Viewing your app on your phone
6. Point the camera at the QR code that is
displayed in the Expo UI on the computer.
Once the code is scanned, new logs and a
new connected device in the Expo UI can be
noticed.
7. The device is listed on the left side of this
screen and the logs on the right side indicates
that a JavaScript bundle has finished building
Viewing your app on your phone
8. Then, you can return to your device and you should see your
app running.
9. Expo setup enables live reloading for free on physical devices
synchronized with code updates on the computer.
Editing your app
1. Open up the App.js file inside the my-project folder:
1. We import React from the react package
2. We import the StyleSheet, View and Text
components from the react-native
package which are part of React Native.
• StyleSheet allows to create a style in react
native the app (same as CSS)
• Text allows to display text.
• View container element like DIV in HTML.
Without it, nothing will be displayed.
3. The App.js always has the "export
default function" header.
4. We apply the styles.container style to the
View.
5. StyleSheet.create method will create a
style sheet and assign it to the variable
styles.
6. You can create many style sheets and
named it as: container, title…etc
Editing your app
2. Make a small style change to make the font bold:
Viewing your app on your phone
3. .A new style called “text” is added and applied to
the Text component. The change can be visualized
in the device application concurrently.
• Next → Running React Native apps on a variety of
virtual device emulators using the Expo Snack
service.
Viewing your app on Expo Snack
Viewing your app on Expo Snack
• Expo Snack is an open-source platform for running React Native apps in the
browser.
• Expo snack lets you to run complete react native projects in the browser.
• The Snack service provided by Expo is a playground for React Native code.
• Codes is saving as "Snacks"
• It aids to organize the React Native project.
• The Expo account can be created on Snacks and save the work to keep working
on them or sharing them with others.
• It is also possible to import code that is stored locally into a Snack or a Git
repository.
• When the URL is opened, Snack interface will be loaded and enables to make
changes to the code to test things out before running them.
• The significant of Snack is the ability to easily run them on virtualized devices.
Expo Snack-Interface
Expo Snack can be access using: https://snack.expo.dev/

File structure
Coding area Emulator
Expo Snack-Interface
• The controls to run the app on a virtual device can
be found on the right side of the UI as shown:
• The top control above the image of the phone
controls which device type to emulate: My Device,
Android, iOS, or Web.
• The Tap to play button will launch the selected
virtual device.
Expo Snack-Interface
• Here's what our app looks like on a virtual • Here's what our app looks like on a virtual
Android device: iOS device:

• This app only displays text and applies some styles to it, so it looks pretty much identical on different platforms.
Introducing React Native styles
Introducing React Native styles
• Here, we will review using React
Native style sheets before we start
implementing in the next section.
• Create a React Native style sheet
named file styles.js and saved it under
components folder.
• Add the following code inside of
styles.js file.
• This is a JavaScript module, not a CSS
module.
• Use plain objects to declare React
Native styles.
• Call StyleSheet.create() and export this
from the style module.
• Style sheet has three styles: container,
box, and boxText.
Introducing React Native styles
• Call to Platform.select() function inside the
container style.
• This function will return different styles based on the
platform of the mobile device.
• .The function handling the top padding of the top-
level container view.
• .This code is used in most of the apps : ensures that
React components don't render underneath the
status bar of the device.
• The padding vary based on the platform.
• IOS: paddingTop is 20.
• Android: paddingTop is 100.
Introducing React Native styles
• Let's see how these styles are imported and applied to React
Native components.
• Add the following code inside of App.js file.
• The styles are assigned to each component via the style
property.

Output in Output in
Android iOS
Flexbox - new layout standard

Chapter-15
Flexbox - new layout standard
• Flexbox is box/layout model .that is flexible to
provide a workable layout.
• A flexbox arranges elements in an efficient and
dynamic manner while giving them equal
distributed spaces inside a container.
• Box - acts as a container that holds the child
elements.
• .Child elements are flexible according to the pattern
it is to be rendered on the screen.
• Flexbox containers have a direction, either Column
(up/down) or Row (left/right).
• .Rows stack on top of one another!
• .The key concept - it's the direction that the box
flexes, not the direction that boxes are placed on
the screen.
Building Flexbox layouts
• Using flexbox, you can design the layout that best flexbox

suits the application.


• Here, we will see how powerful the Flexbox layout
model is for mobile screens.
Building Flexbox layouts
*Simple three-column (sections) layout
• Let's implement a simple layout with three sections that
flex in the direction of the column (top to bottom).
• Let's start by taking a look at the resulting screen:
• The idea, in this example, is that you've styled and
labeled the three screen sections so that they stand
out. In other words, these components wouldn't
necessarily have any styling in a real application since
they're used to arrange other components on the
screen.
Components used to create this screen layout:
1. The container view (the outermost <View> component) is the column.
2. The child views are the rows.
3. The <Text> component is used to label each row.
4. In terms of HTML elements:
1. <View> is similar to a <div> element while
2. <Text> is similar to a <p> element.
4. Add the following code inside of App.js file.
Styles used to create this layout:
• Create a React Native style sheet named file styles.js and saved it under
components folder.
• Add the following code inside of styles.js file.

• The flex and flexDirection


properties of container enable the layout
of the rows to flow from top to bottom.
• .The alignItems and
justifyContent properties align the
child elements to the center of the
container and add space around them.
• When the device is rotated from a portrait
orientation to a landscape orientation, the
Flexbox automatically figured out how to
preserve the layout.

Output in
iOS
Improved three-column (section) layout
• The key change here is the alignSelf property in
style.js file.
• This tells elements with the box style to change
their width or height (depending on flexDirection of
their container) to fill space.
• .Also, the box style no longer defines a width
property because this will be computed on the fly now.
• .Here's what the sections look like in portrait mode:

Output in
iOS
Flexible rows
• Flexible row – Enables to create screen layout
sections stretch from top to bottom.
• Here is what content of styles.js file and the styles
for this screen look like:
• The three columns stretch
all the way from the top of
the screen to the bottom of
the screen because of the
alignSelf property, which
doesn't actually specify
which direction to stretch in.
• The three box components
stretch from top to bottom
because they're displayed
in a flex row.
Flexible grids
• Sometimes, you need a screen layout that flows
like a grid.
• For example, what if you have several sections
that are the same width and height, but you're With
not sure how many of these sections will be Flexible grids
rendered in prior (advance)?
• The Flexbox makes it easy to build a row that flows
from left to right until the end of the screen is
reached.
• It Visualizing the screen layout as a grid.
• Then, it automatically continues rendering elements
from left to right on the next row.

Without
Flexible grids
Flexible grids • styles.js used to create this layout:

• App.js used to create this layout:


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 12

The React Component Life Cycle


Contents
1.Why components need a life cycle
2.Lifecycles of Component
3.Containing errors with error boundaries
Weekly Learning Outcomes

1. Explain the life cycle of React components


2. Explain how to write code that responds to life cycle
events
Required Reading
1. Chapter 7 (React and React Native: A complete
hands-on guide to modern web and mobile
development with React.js,3rd Edition, 2020, Adam
Boduch, Roy Derks)

Recommended Reading
React.Component: https:/ / reactjs. org/ docs/ react- component.
Html

State and Lifecycle: https:/ / reactjs. org/ docs/ state- and-


lifecycle. html
Why components need a life cycle
Why components need a life cycle
• React components go through a life cycle.
• render() method that is implemented in components is a life cycle method.
• Rendering is just one life cycle event in a React component.
• For example, there are life cycle events for when the component is mounted to the
DOM, when the component is updated.
• .Life cycle events are moving part.
• Some components do need to respond to life cycle events such as:
1. Perform initialization.
2. Unmounted from the DOM.
3. Handle errors thrown by the component.
4. Clean up the component.
Lifecycles of Component
Lifecycle of Components
• React components go through a life cycle.
• In React, Life cycle of a component represents the different stages of the
component during its existence.
• React provides callback methods to attach functionality in each and every stages
of the React life cycle.
• .Each component in React has a lifecycle which you can monitor and manipulate
during its three main phases.
• The three phases/stages are: Mounting, Updating, and Unmounting.
Mounting phase
• Mounting means putting elements into the DOM.
• React has four built-in methods that gets called, in this order, when mounting a
component:
1.constructor()
2.getDerivedStateFromProps()
3.render()
4.componentDidMount()

• The render() method is required and will always be called, the others are
optional and will be called if you define them.
Mounting phase: constructor()
• The constructor() method is called when the component is initiated, and it is the natural place to
set up the initial state and other initial values.
• The constructor method is called, by React, every time you make a component:
• The constructor() method is called with the props, as arguments, and you should always start by
calling the super(props) before anything else.
• This will initiate the parent's constructor method and allows the component to inherit methods from its
parent (Component).
Mounting phase: getDerivedStateFromProps()
• The getDerivedStateFromProps() method
is called right before rendering the
element(s) in the DOM.
• getDerivedStateFromProps() method
allows you to update the state of the
component based on the property values
of the component.
• This method is called when the
component is initially rendered and when
it receives new property values.
• The example (right) starts with the
favorite course being “IT448", but
the getDerivedStateFromProps() method
updates the favorite course based on
the favcor attribute:
Mounting phase: render
• The render() method is required, and is the method that actually outputs the HTML/XML to the
DOM.
• A simple component with a simple render() method:
Mounting phase: componentDidMount
• The componentDidMount()
method is called after the
component is rendered.
• This is where you run
statements that requires
that the component is
already placed in the
DOM.
• For example: At first my
favorite course is IT448,
but give me a 2 second,
and it is IT210 instead:

After 2000 millisecond (2 s)


Updating phase
• The next phase in the lifecycle is when a component is updated.
• A component is updated whenever there is a change in the component's state or props.
• React has five built-in methods that gets called, in this order, when a component is updated:

1.shouldComponentUpdate()
2.getDerivedStateFromProps()
3.render()
4.getSnapshotBeforeUpdate()
5.componentDidUpdate()

• The render() method is required and will always be called, the others are optional and will be
called if you define them.
Updating phase: shouldComponentUpdate()
• In the shouldComponentUpdate() method
you can return a Boolean value that
specifies whether React should continue
with the rendering or not.
• The default value is true.
• The example below shows what happens
when
the shouldComponentUpdate() method
returns false:
Updating phase: getDerivedStateFromProps()
• getDerivedStateFromProps() method invoked during update phase and just
before the render() method.
• It is rarely used where the changes in properties results in state change.
• It is mostly used in animation context where the various state of the component
is needed to do smooth animation.
Updating phase: getSnapshotBeforeUpdate
• In the getSnapshotBeforeUpdate() method, you have access to
the props and state before the update, meaning that even after the update, you
can check what the values were before the update.
• If the getSnapshotBeforeUpdate() method is present, you should also include
the componentDidUpdate() method, otherwise you will get an error.

Updating phase: componentDidUpdate()


• The componentDidUpdate method is called after the component is updated in
the DOM.
• It's rare that you'll have to use this method.
Unmounting phase
• The next phase in the lifecycle is
when a component is unmounting
(removed) from the DOM.
• React has only one built-in
method that gets called when a
component is unmounted:
1.componentWillUnmount()
• The componentWillUnmount
method is called when the
component is about to be
removed from the DOM.
• You can think of this method
as a way to clean up anything
that is needed to be removed
before the component is
destroyed.
Containing errors with error boundaries
React Error Boundaries
• In the past, if we get any JavaScript errors inside components, it corrupts the
React app and the user would just see a blank web page, which is not ideal!
• React 16 introduces a new concept to handle the errors by using the error
boundaries. Now, if any JavaScript error found in a part of the UI, it does not break
the whole React app.
• Error boundaries is a mechanism used to for handling errors in React components.
• Error boundaries can catch JavaScript errors anywhere in our app, log those
errors, and display a fallback UI.
• Error boundaries similar to try…catch syntax for JSX.
• A class component becomes an error boundary if it defines the
componentDidCatch() method
• Use componentDidCatch() to log error information.
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 14

Geolocation, Maps and Sensors


Contents
1.Where am I?
2.What's around me?
3.Annotating points of interest
4.Sensors overview
5.Motion sensor
6.Position sensor
7.Environment sensor
Weekly Learning Outcomes
1. Explain about the geolocation and mapping capabilities of
React Native
2. Explain the basic configuration MapView components
3. Describe various types of sensors
Required Reading
1. Chapter 19 (React and React Native: A complete hands-on
guide to modern web and mobile development with
React.js,3rd Edition, 2020, Adam Boduch, Roy Derks) and
Sensors (Android Developer Website)

Recommended Reading
Geolocation: https:/ / facebook. github. io/ react- native/ docs/
geolocation
React Native maps: https:/ / github. com/ react- community/ react-
native- maps
Where am I?
Where am I?
• The geolocation API is uses by web applications to figure out the location of the
user.
• .geolocation API used by React Native applications because the same API has
been polyfilled in React Native applications.
• This API is useful for getting precise coordinates from the GPS on mobile devices.
• The API information is used to display meaningful location data to the user.
• Unfortunately, the data (latitude and longitude) that's returned by the geolocation API is
of little use on its own.
• For example, latitude and longitude don't mean anything to the user, but you can use this data to look
up something that is of use to the user (i.e. user address information).
• This might be as simple as displaying where the user is currently located.
Where am I?
• Let's implement an example that uses the
geolocation API of React Native to look up
coordinates and then use those coordinates to
look up human-readable location information from
the Google Maps API:
• The goal of this component is to render the
properties returned by the geolocation API on the
screen, as well as look up the user's specific
location, and display it.
• The setPosition() function is used as a
callback in a couple of places. Its job is to set the
state of your component.
• First, setPosition() sets the lat-long coordinates.
• Normally, you wouldn't display this data directly, but this is an
example that's showing the data that's available as part of the
geolocation API.
Where am I?
• .Second, setPosition() uses the latitude
and longitude values to look up the
name of where the user is currently,
using the Google Maps API.
• The setPosition() callback is used with
getCurrentPosition(), which is
only called once when the component is
mounted.
• You're also using setPosition() with
watchPosition(), which calls the
callback any time the user's position
changes.
Where am I?
• View of the Screen loaded with the
location data:
• The address information that was
fetched is probably more useful in an
application than latitude and longitude
data.
What's around me?
What's around me?
• The MapView component from
react-native-maps is the main tool
you'll use to render maps in your
React Native applications.
• The two Boolean properties that
you've passed to MapView:
1. The showsUserLocation property
will activate the marker on the map,
which denotes the physical location
of the device running this
application.
2. The followUserLocation property
tells the map to update the location
marker as the device moves around.
• The resulting map:

• .The current location of the device is clearly marked on the map.


• .By default, points of interest are also rendered on the map.
• .These are things in close proximity to the user so that they can see what's around them.
• .It's generally a good idea to use the followUserLocation property whenever using showsUserLocation.
• .This makes the map zoom to the region where the user is located.
Annotating points of interest
Annotating points of interest
• Annotations → is additional information rendered on top of the basic map geography.
• .You get annotations, by default, when MapView components are rendered.
• .The MapView component can render the user's current location and points of interest
around the user.
• .The challenge here is that you probably want to show points of interest that are relevant
to your application, instead of the points of interest that are rendered by default.
Plotting points
• .Here is you pass annotations to the MapView
component:
• .Setting the showsPointsOfInterest property to false.
• The callout is displayed when the marker is clicked that
shows the location of the place on the map.
• The text is render based on the description property values
given to <MapView.Marker>

My Home
My home at Glengrove Rd

My Work
My Work at Kingston Rd
Sensor's overview
Sensors - overview
• Android-powered devices have built-in sensors that measure motion, orientation, and
various environmental conditions.
• These sensors capable of providing raw data with high precision and accuracy.
• These sensors are useful to monitor three-dimensional device movement or positioning, or
changes in the ambient (around) environment near a device.
• Examples:
1. A game might track readings from a device's gravity sensor to infer complex user gestures
‫ ايماءات‬and motions, such as tilt ‫ميالن‬, shake, rotation, or swing.
2. A weather application use a device's temperature sensor and humidity sensor to calculate
and report the dewpoint.
3. Travel application use the geomagnetic field sensor and accelerometer to report a compass
bearing.
Introduction to Sensors
• The sensor framework provides several classes and interfaces that help you
perform a wide variety of sensor-related tasks.
• Android sensor framework can use to access many types of sensors available
on the device.
• Sensors: hardware-based and some are software-based.
1. Hardware-based sensors are physical components built into a handset or
tablet device.
• Hardware-based sensors derive their data by directly measuring specific environmental
properties, such as acceleration, geomagnetic field strength, or angular change.
2. Software-based sensors are not physical devices.
• Software-based sensors derive their data from one or more of the hardware-based sensors
and are sometimes called virtual sensors or synthetic/fake sensors.
• .The linear acceleration sensor and the gravity sensor are examples of software-based
sensors.
Table 1. Sensor types supported by the Android platform.

Sensor Type Description Common Uses


Measures the acceleration force in m/s2 that is applied
TYPE_
Hardware to a device on all three physical axes (x, y, and z), Motion detection (shake, tilt, etc.).
ACCELEROMETER
including the force of gravity.

TYPE_ Measures the ambient room temperature in degrees


Hardware Monitoring air temperatures.
AMBIENT_TEMPERATURE Celsius (°C).

.TYPE_ Software or Measures the force of gravity in m/s2 that is applied to


Motion detection (shake, tilt, etc.).
GRAVITY Hardware a device on all three physical axes (x, y, z).

TYPE_ Measures a device's rate of rotation in rad/s around


Hardware Rotation detection (spin, turn, etc.).
GYROSCOPE each of the three physical axes (x, y, and z).

TYPE_
Hardware Measures the ambient light level (illumination) in lx. Controlling screen brightness.
LIGHT

Measures the acceleration force in m/s2 that is applied


.TYPE_ Software or Monitoring acceleration along a single
to a device on all three physical axes (x, y, and z),
LINEAR_ACCELERATION Hardware axis.
excluding the force of gravity.

TYPE_ Measures the ambient geomagnetic field for all three


Hardware Creating a compass.
MAGNETIC_FIELD physical axes (x, y, z) in μT.
Table 1. Sensor types supported by the Android platform. Cont…

Measures degrees of rotation that a device makes around all


three physical axes (x, y, z). As of API level 3 you can obtain the
TYPE_
Software inclination matrix and rotation matrix for a device by using the Determining device position.
ORIENTATION
gravity sensor and the geomagnetic field sensor in conjunction
with the getRotationMatrix() method.

TYPE_
Hardware Measures the ambient air pressure in hPa or mbar. Monitoring air pressure changes.
PRESSURE

Measures the proximity of an object in cm relative to the view


TYPE_
Hardware screen of a device. This sensor is typically used to determine Phone position during a call.
PROXIMITY
whether a handset is being held up to a person's ear.

TYPE_
RELATIVE_HUMIDI Hardware Measures the relative ambient humidity in percent (%). Monitoring dewpoint, absolute, and relative humidity.
TY
.TYPE_
Software or Measures the orientation of a device by providing the three
ROTATION_VECTO Motion detection and rotation detection.
Hardware elements of the device's rotation vector.
R

Measures the temperature of the device in degrees Celsius (°C).


.TYPE_ This sensor implementation varies across devices and this
Hardware
TEMPERATURE sensor was replaced with the
TYPE_AMBIENT_TEMPERATURE sensor in API Level 14
Sensors Framework
• We can access these sensors and acquire raw sensor data by using the Android sensor
framework.
• The sensor framework includes the following classes and interfaces:
• SensorManager
▪ Accessing/listing sensors
▪ Registering/unregistering sensor event listeners
▪ Acquiring orientation information
• Sensor
▪ Determining the capability of sensors
• SensorEvent
▪ Providing information about sensor events
▪ Including raw sensor data, sensor, the accuracy, and timestamp.
• SensorEventListener
▪ Containing callbacks to receiving notifications of sensor events
Sensor Coordinate System
• The sensor framework uses a standard 3-axis
coordinate system to express data values.
• X axis – horizontal pointing right
• Y axis – vertical pointing up
• Z axis – pointing toward the outside of the
screen face.
• Coordinate system does not change when
orientation changes.
• getOrientation() method uses to determine
screen rotation.
• remapCoordinateSystem()method use to
map sensor coordinates to screen coordinates.
Motion sensors
Motion sensors
• Motion sensors monitor the motion of a device.
• Includes accelerometers, gravity sensors, gyroscopes ‫تحديد االتجاه‬, and rotational
vector sensors.
• The sensors' possible architectures vary by sensor type:
1. The gravity, linear acceleration, rotation vector, step counter, and step detector
sensors are either hardware-based or software-based.
2. .The accelerometer and gyroscope sensors are always hardware-based.
• Software-based sensors: rely on one or more hardware sensors to derive their
data.
• Derive their data either from the accelerometer or from the gyroscope.
Motion sensors
• Motion sensors are useful for monitoring device movement, such as tilt, shake, rotation,
or swing.
• The movement is either:
1. A reflection of direct user input (for example, a user steering a car in a game or a user controlling a ball
in a game).
2. A reflection of the physical environment in which the device is sitting (for example, moving with you
while you drive your car).
• .Motion sensors by themselves are not typically used to monitor device position, but they
can be used with other sensors.
• All of the motion sensors return multi-dimensional arrays of sensor values for each
Sensor Event.
• .For example, during a single sensor event, the accelerometer returns acceleration force data for the
three coordinate axes, and the gyroscope returns rate of rotation data for the three coordinate axes.
Position sensors
Position sensors
• Position sensors measure the physical position of a device.
• Two hardware-based sensors to determine the position of a device:
▪ Geomagnetic field sensor and the accelerometer.
• Proximity sensor: To determine how close the face of a device is to an object
• Most handset and tablet manufacturers include a geomagnetic field sensor.
• .For determining a device's orientation, you can use the readings from the
device's accelerometer and the geomagnetic field sensor.
• .Position sensors do not monitor device movement or motion, such as shake, tilt,
or thrust.
Environment sensors
Environment sensor
• Environment sensors measure various environmental parameters.
• Four sensors to monitor various environmental properties such as temperature,
pressure, illumination/light, and humidity.
• All four environment sensors are hardware-based and are available only if a
device manufacturer has built them into a device.
• With the exception of the light sensor, which most device manufacturers use to control screen
brightness.
• Environment sensors return a single sensor value for each data event.
• For example, the temperature in °C or the pressure in hPa.
• Environment sensors do not typically require any data filtering or data processing.
Thank You

You might also like