IT448 New Slide
IT448 New Slide
Week 2
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
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
• *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:
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
Week 3
26/12/2021
College of Computing and Informatics
Bachelor of Science in Computer Science
Week 5
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.
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
Week 6
• 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).
@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
• 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
Scroll
down
Thank You
ر
الجامعة السعودية االلكتونية
ر
االلكتونية الجامعة السعودية
26/12/2021
College of Computing and Informatics
Bachelor of Science in Computer Science
Week 7
<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);
• 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.
<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.
// 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();
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
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.
<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) {
// 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dm = new DataManager(this);
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
Week 9
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
Week 10
Recommended Reading
Introducing JSX: https:/ / reactjs. org/ docs/ introducing- jsx. Html
Hello, JSX
26/12/2021
College of Computing and Informatics
Bachelor of Science in Computer Science
Week 11
• 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.?
// MyFunction.js
• 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
Week 13
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:
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
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:
26/12/2021
College of Computing and Informatics
Bachelor of Science in Computer Science
Week 12
Recommended Reading
React.Component: https:/ / reactjs. org/ docs/ react- component.
Html
• 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:
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.
26/12/2021
College of Computing and Informatics
Bachelor of Science in Computer Science
Week 14
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:
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.
TYPE_
Hardware Measures the ambient light level (illumination) in lx. Controlling screen brightness.
LIGHT
TYPE_
Hardware Measures the ambient air pressure in hPa or mbar. Monitoring air pressure changes.
PRESSURE
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