Download as pdf or txt
Download as pdf or txt
You are on page 1of 78

Chapter One: Android Overview

April 15, 2024 Mobile Application Development - Elias Debelo 1


Android Overview: History
• “Android is an Operating System (OS) that is used in Smartphone.”
AKA, Modified Version of LUNIX KERNEL.
• Begin in 2003 by Android Inc., to develop OS for digital cameras.

• In 2004 the project changed to become OS for Smartphones.


• Google bought Andoid Inc. in 2004. Then Google decided to base
anroid on LUNIX. (which is Open Source).

April 15, 2024 Mobile Application Development - Elias Debelo 2


Android Overview: History
• On November 5, 2007, Google announced the founding of the Open
Handset Alliance, a consortium of dozens of technology and mobile
telephone companies.

• Now, Android is developed by a consortium of developers known as the


Open Handset Alliance and commercially sponsored by Google.

• It is free and open-source software; its source code is known as Android


Open Source Project (AOSP), which is primarily licensed under the
Apache License.

April 15, 2024 Mobile Application Development - Elias Debelo 3


Android Overview: Android Market
• According to Statcounter (January 2024)

April 15, 2024 Mobile Application Development - Elias Debelo 4


Android Overview: Future
Some of them:
1. Beautiful UI
2. Connectivity
3. Storage
4. Media support
5. Messaging
6. Multi-touch
And More

April 15, 2024 Mobile Application Development - Elias Debelo 5


Example: Connectivity
• In addition to providing standard network connectivity, Android
provides APIs to let your app connect and interact with other
devices with protocols such as Bluetooth, NFC, Wi-Fi P2P, USB, and
SIP.

• GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, LTE and WiMAX

April 15, 2024 Mobile Application Development - Elias Debelo 6


Why Android?

April 15, 2024 Mobile Application Development - Elias Debelo 7


Platform Architecture

April 15, 2024 Mobile Application Development - Elias Debelo 8


Android Software
Stack
• The Lunix Kernel (LK)
E.g., Android Runtime (ART)
Relies on LK. Tasks like threads and
Memory management.
• The hardware abstraction
layer (HAL) - provides standard
interfaces that expose device
hardware capabilities to the
higher-level Java API framework.

April 15, 2024 Mobile Application Development - Elias Debelo 9


Cont.
• Android Runtime - for devices running Android version 5.0 (API
level 21) or higher, each app runs in its own process and with its own
instance of the Android Runtime (ART).

• ART is written to run multiple virtual machines on low-memory


devices by executing DEX files, a bytecode format designed specially
for Android that's optimized for minimal memory footprint.
• Feature of ART includes background tasks like Optimized garbage
collection (GC).

April 15, 2024 Mobile Application Development - Elias Debelo 10


Cont.
• Native C/C++ Libraries - many core Android system components
and services, such as ART and HAL, are built from native code that
require native libraries written in C and C++.

• The Android platform provides Java framework APIs to expose the


functionality of some of these native libraries to apps.

• For example, you can access OpenGL ES through the Android


framework’s Java OpenGL API to add support for drawing and
manipulating 2D and 3D graphics in your app.

April 15, 2024 Mobile Application Development - Elias Debelo 11


Cont.
• Java API Framework - The entire feature-set of the Android OS is
available to you through APIs written in the Java language.
• These APIs form the building blocks you need to create Android
apps by simplifying the reuse of core, modular system
components and services, which include the following:
✓ View System (for UI)
✓ Resource Manager (e.g., layouts)
✓ Notification Manager (e.g., alerts)
✓ Activity Manager (e.g., app lifecyle)
✓ Content Manager (e.g., accessing data from app)

April 15, 2024 Mobile Application Development - Elias Debelo 12


Cont.
• System Apps - Android comes with a set of core apps for email,
SMS messaging, calendars, internet browsing, contacts, and more.

• The system apps function both as apps for users and to provide key
capabilities that developers can access from their own app.

• For example, if your app would like to deliver an SMS message, you
don't need to build that functionality yourself—you can instead
invoke whichever SMS app is already installed to deliver a message to
the recipient you specify.

April 15, 2024 Mobile Application Development - Elias Debelo 13


What can
we do
with
android?

April 15, 2024 Mobile Application Development - Elias Debelo 14


Installations

developer.android.com/studio

April 15, 2024 Mobile Application Development - Elias Debelo 15


Android Installation: Android Studio
• Google Recommended Android App Development IDE.
• Support JAVA and KOTLIN Languages. Both can also be used for
Runtime UI Designs.

• Current Stable Version is Android Studio Hedgehog|


2023.1.1
• It is Fast and Lightweight
• Powered by The IntelliJ® Platform
April 15, 2024 Mobile Application Development - Elias Debelo 16
Android Installation: Necessary Tools
• SDK Platform Package - includes android platform and source
pertaining to API level by default. We need to install at least one
of these.
E.g.,
✓Android 14.0 (UpsideDownCake) – Latest as of today
✓Android 11.0 (R)
✓Android 8.0 (Orio)
✓Android 5.0 (Lollipop)

April 15, 2024 Mobile Application Development - Elias Debelo 17


Android Installation: Necessary Tools
• SDK TOOLS - is a component for the Android SDK. It
includes development and debugging tools for Android
developers.
E.g.,
✓Android SDK Build-Tools
✓Android Emulator
✓Android SDK Platform-Tools

April 15, 2024 Mobile Application Development - Elias Debelo 18


Testing First App
• Create new app

April 15, 2024 Mobile Application Development - Elias Debelo 19


Architectural Design Patterns
• Common Design Patterns Are;
✓ MVC (Model — View — Controller)
✓ MVP (Model — View — Presenter)
✓ MVVM (Model — View — ViewModel)

• The main idea of all these patterns is to organize the project in a proper way so
that all the codes get covered in the Unit Testing.

• Moreover, it is very helpful in the maintenance of the software, to add and


remove features and developers can keep a track of various crucial logic parts.

April 15, 2024 Mobile Application Development - Elias Debelo 20


Cont.

• MVC (Model — View — Controller) - MVC pattern is the oldest android app
architecture which simply suggests separating the code into 3 different layers:

• Model: Layer for storing data. It is responsible for handling the domain logic(real-
world business rules) and communication with the database and network layers.

• View: UI(User Interface) layer. It provides the visualization of the data stored in the
Model.

• Controller: Layer which contains core logic. It gets informed of the user’s behavior
and updates the Model as per the need.

April 15, 2024 Mobile Application Development - Elias Debelo 21


Cont.
▪ Advantages
• MVC pattern increases the code testability and makes it easier to implement new
features as it highly supports the separation of concerns.
• Unit testing of the Model and Controller
is possible as they do not extend or use any Android class.
• Functionalities of the View can be
checked through UI tests if the
View respect the single responsibility principle.
▪ Disadvantages:
• Code layers depend on each other even if MVC is applied correctly.
• No parameter to handle UI logic i.e., how to display the data.

April 15, 2024 Mobile Application Development - Elias Debelo 22


Cont.
• The Model—View—Presenter(MVP) Pattern - MVP pattern is the second iteration
of Android app architecture.
• This pattern is widely accepted and is still recommended for upcoming developers.
• The purpose of each component is easy to learn:
• Model: Layer for storing data. It is responsible for handling the domain logic(real-world business
rules) and communication with the database and network layers.
• View: UI(User Interface) layer. It provides the visualization of the data and keep a track of the
user’s action in order to notify the Presenter.
• Presenter: Fetch the data from the model and applies the UI logic to decide what to display. It
manages the state of the View and takes actions according to the user’s input notification from
the View.

April 15, 2024 Mobile Application Development - Elias Debelo 23


Cont.
• In the MVP schema, View and Presenter are closely related and have a reference to each other.
To make the code readable and easier to understand, a Contract interface class is used to define
the Presenter and View relationship. The View is abstracted and has an interface in order to
enable the Presenter for Unit Testing.
• Advantages
• No conceptual relationship in android
components
• Easy code maintenance and testing as the
application’s model, view, and presenter
layer are separated.
• Disadvantages - If the developer does not follow the single responsibility principle to break the
code then the Presenter layer tends to expand to a huge all-knowing class.

April 15, 2024 Mobile Application Development - Elias Debelo 24


Cont.
• The Model—View—ViewModel (MVVM) Pattern - The third iteration of android architecture
is the MVVV pattern.
• While releasing the Android Architecture Components, the Android team recommended this
architecture pattern. Below are the separate code layers:
• Model: This layer is responsible for the abstraction of the data sources. Model and
ViewModel work together to get and save the data.
• View: The purpose of this layer is to inform the ViewModel about the user’s action.
• ViewModel: It exposes those data streams which are relevant to the View.
• The MVVM and MVP patterns are quite similar because both are efficient in abstracting the
state and behavior of the View layer. In MVVM, Views can bind itself to the data streams which
are exposed by ViewModel.

April 15, 2024 Mobile Application Development - Elias Debelo 25


Cont.
• In MVVM schema the View informs the ViewModel about various actions. The
View has a reference to the ViewModel while ViewModel has no information
about the View.
• The many-to-one relationship that
exists between View and ViewModel
and MVVM supports two-way data
binding between both.

April 15, 2024 Mobile Application Development - Elias Debelo 26


Cont.
▪ Advantages of Architecture
• Developers can design applications that can accept changes in the future.
• Gives a modular design to the application which assures good quality testing
and maintenance of code.
▪ Disadvantages of Architecture
• Writing the whole project code in an architecture pattern is a time taking
process.
• Strict discipline is required from the developer team side as one misplaced
change can ruin the integrity of the architecture.

April 15, 2024 Mobile Application Development - Elias Debelo 27


UI Architecture – Context
• Context - Interface to global information about an application environment.
This is an abstract class whose implementation is provided by the Android
system.
• It allows access to application-specific resources and classes, as well as up-calls
for application-level operations such as launching activities, broadcasting and
receiving intents, etc.
• Simply put, Context is a vital conduit between your Android application and the
underlying Android system.
• Proper understanding and use of Context can make the difference between a
smoothly running app and one error prone with memory leaks and crashes.
• Two Type: Activity Context and Application Context

April 15, 2024 Mobile Application Development - Elias Debelo 28


UI Architecture – Activity Context
• Each Activity in Android comes with its own Context, which is intrinsically tied
to the lifecycle of that Activity.
• This Context is ideally used to perform operations that have a scope confined to
the Activity itself, such as manipulating UI elements within that Activity.
• It is tied to the life cycle of activity. It is used for the current Context. The method of invoking
the Activity Context is getContext().
• Some use cases of Activity Context are:
• The user is creating an object whose lifecycle is attached to an activity.
• Whenever inside an activity for UI related kind of operations like toast, dialogue, etc.,
• getContext():
• It returns the Context which is linked to the Activity from which it is called. This is useful
when we want to call the Context from only the current running activity.
April 15, 2024 Mobile Application Development - Elias Debelo 29
UI Architecture – Application Context
• In contrast to the Activity Context, the Application Context is tied to
the lifecycle of the application. It extends beyond any single Activity
or UI-related operations.
• The Application Context is generally used for operations intended to
be global across the application, like initializing singletons that need
a Context or if you need to perform an operation outside the lifecycle
of the current Activity.
• It remains as long as your application is alive, which makes it safe to
use in long-living components like ViewModels.

April 15, 2024 Mobile Application Development - Elias Debelo 30


Cont.
• However, do note that using the Application Context may not be suitable for all operations. Some
UI-related tasks, such as creating dialogs or toasts, require an Activity Context. Attempting these
operations with an Application Context may lead to issues.
• accessed via getApplicationContext(). Some use cases of Application Context
are:
• If it is necessary to create a singleton object
• During the necessity of a library in an activity
• List of functionalities of Application Context:
• Load Resource Values
• Start a Service
• Bind to a Service
• Send a Broadcast
• Register BroadcastReceiver
April 15, 2024 Mobile Application Development - Elias Debelo 31
UI Architecture - Intent
• An Intent is a messaging object you can use to request an action from another
app component. Although intents facilitate communication between components
in several ways, there are three fundamental use cases:
• Start Activity - This is to launch a new activity or get an existing activity to
be action.
• Starting a service - This is to start a new service or deliver instructions for an
existing service.
• Delivering a broadcast - This is to deliver the message to broadcast receivers.
• Below are some applications of Intents:
• Sending the User to Another App
• Getting a Result from an Activity
• Allowing Other Apps to Start Your Activity
April 15, 2024 Mobile Application Development - Elias Debelo 32
Cont.
• Explicit intents - specify which component of which application will satisfy the
intent, by specifying a full ComponentName.
• You'll typically use an explicit intent to start a component in your own app,
because you know the class name of the activity or service you want to start. For
example, you might start a new activity within your app in response to a user
action, or start a service to download a file in the background.
• Implicit intents - do not name a specific component, but instead declare a
general action to perform, which allows a component from another app to handle
it.
• For example, if you want to show the user a location on a map, you can use an
implicit intent to request that another capable app show a specified location on a
map.
April 15, 2024 Mobile Application Development - Elias Debelo 33
UI Architecture – Activity
• Activity - An activity is a single, focused thing that the user can do. Almost all
activities interact with the user, so the Activity class takes care of creating a
window for you in which you can place your UI with setContentView(View).
• While activities are often presented to the user as full-screen windows, they can
also be used in other ways: as floating windows (via a theme with
R.attr.windowIsFloating set), Multi-Window mode or embedded into other windows.
• There are two methods almost all subclasses of Activity will implement:
• onCreate(Bundle)
• onPause()
• To be of use with Context.startActivity(), all activity classes must have a
corresponding <activity> declaration in their package's AndroidManifest.xml.

April 15, 2024 Mobile Application Development - Elias Debelo 34


UI Architecture – Fragment
• A Fragment represents a reusable portion of your app's UI. A fragment defines
and manages its own layout, has its own lifecycle, and can handle its own input
events.
• Fragments can't live on their own. They must be hosted by an activity or another
fragment. The fragment’s view hierarchy becomes part of, or attaches to, the
host’s view hierarchy.
• For Modularity - Fragments introduce modularity and reusability into your activity’s
UI by letting you divide the UI into discrete chunks. Activities are an ideal place to put
global elements around your app's user interface, such as a navigation drawer. Conversely,
fragments are better suited to define and manage the UI of a single screen or portion of
a screen.

April 15, 2024 Mobile Application Development - Elias Debelo 35


UI Architecture – Activity Lifecyle
• Activities in the system are managed as activity stacks.
• When a new activity is started, it is usually placed on the top of the current stack and
becomes the running activity -- the previous activity always remains below it in the stack,
and will not come to the foreground again until the new activity exits.
• There can be one or multiple activity stacks visible on screen.
• An activity has essentially four states:
✓ If an activity is in the foreground of the screen (at the highest position of
the topmost stack), it is active or running. This is usually the activity that the
user is currently interacting with.

April 15, 2024 Mobile Application Development - Elias Debelo 36


Cont.
✓ If an activity has lost focus but is still presented to the user, it is visible. It is
possible if a new non-full-sized or transparent activity has focus on top of
your activity, another activity has higher position in multi-window mode, or
the activity itself is not focusable in current windowing mode.
Such activity is completely alive (it maintains all state and member information and
remains attached to the window manager).
✓ If an activity is completely obscured by another activity, it is stopped or hidden.
It still retains all state and member information, however, it is no longer visible
to the user so its window is hidden and it will often be killed by the system when
memory is needed elsewhere.

April 15, 2024 Mobile Application Development - Elias Debelo 37


Cont.
✓ The system can drop the activity from memory by either asking it to
finish, or simply killing its process, making it destroyed. When it is
displayed again to the user, it must be completely restarted and restored to its
previous state.

• The following diagram shows the important state paths of an


Activity. The square rectangles represent callback methods you can
implement to perform operations when the Activity moves between
states. The colored ovals are major states the Activity can be in.

April 15, 2024 Mobile Application Development - Elias Debelo 38


Cont.
• There are three key loops
you may be interested in
monitoring within your activity:
✓ entire lifetime between onCreate and onDestroy
✓ Visible lifetime between onStart and onStop
✓ Foreground lifetime between onResume and
onPause

April 15, 2024 Mobile Application Development - Elias Debelo 39


Cont.
More on Activity Lifecyle
https://developer.android.com/reference/android/app/Activity#Frag
ments

April 15, 2024 Mobile Application Development - Elias Debelo 40


Testing Activity Lifecyle: Using Logcat
• The Logcat window in Android Studio helps you debug your app by displaying
logs from your device in real time—for example, messages that you added to
your app with the Log class, messages from services that run on Android, or
system messages, such as when a garbage collection occurs.
• When an app throws an exception, Logcat shows a message followed by the
associated stack trace containing links to the line of code.
Reading Logcat
• Each log has a date, timestamp, process and thread ID, tag, package name,
priority, and message associated with it.
• Different tags have a unique color that helps identify the type of log. Each log
entry has a priority of FATAL, ERROR, WARNING, INFO, DEBUG, or
VERBOSE.

April 15, 2024 Mobile Application Development - Elias Debelo 41


Android Views & Layouts
A layout defines the structure for a user interface in your app, such as in
an activity.

April 15, 2024 Mobile Application Development - Elias Debelo 42


Cont.
• A View usually draws something the user can see and interact with.
• Whereas a ViewGroup is an invisible container that defines the
layout structure for View and other ViewGroup objects.

• The View objects are usually called "widgets" and can be one of
many subclasses, such as Button or TextView.
• The ViewGroup objects are usually called "layouts" can be one of
many types that provide a different layout structure, such as
LinearLayout, RelativeLayout, ConstraintLayout…

April 15, 2024 Mobile Application Development - Elias Debelo 43


Size, Padding, Margin
• The size of a view is expressed with a width and a
height.
• The padding is expressed in pixels for the left, top, right
and bottom parts of the view.
• Even though a view can define a padding, it does not
provide any support for margins. However, view groups
provide such a support.

April 15, 2024 Mobile Application Development - Elias Debelo 44


Common Layouts

April 15, 2024 Mobile Application Development - Elias Debelo 45


Dynamic Layouts

April 15, 2024 Mobile Application Development - Elias Debelo 46


Linear Layout
• A layout that arranges other views either horizontally in a single column or
vertically in a single row.
• Orientation should be defined, default is horizontal.
• Recommended Height and Width of parent layout is match_parent
• so a vertical list only has one child per row, no matter how wide they are. A
horizontal list is only one row high, and it's the height of the tallest child, plus
padding
• Use android:gravity to align views
• It respect gravity and margin between views

April 15, 2024 Mobile Application Development - Elias Debelo 47


Cont.
• Use layout_gravity to place view on the layout
• Support layout weight of each view using
android:layout_weight
• Layout_weight assigns a number to represent weight of
each view on the layout.
• E.g. Two views can share equal spaces along horizontal if
they have equal layout_weight.

April 15, 2024 Mobile Application Development - Elias Debelo 48


Relative Layout
• The position of each view can be specified as relative to sibling
elements and relative to parent.
• Uses ID to specify relative positioning.
• By default elements draw at top-left corner, overlapping if more than
one.
• Some of the many layout properties:
• android:layout_alignParentTop
• android:layout_centerVertical
• android:layout_below
• android:layout_toRightOf
April 15, 2024 Mobile Application Development - Elias Debelo 49
Homework: Create these form using LinearLayout or RelativeLayout

Signup Form
Signin Form Hello, Solom!

Name

Username
Username
Password

Password

Signup Signin Signout

April 15, 2024 Mobile Application Development - Elias Debelo 50


Chapter Two: More on App Components

April 15, 2024 Mobile Application Development - Elias Debelo 51


Event Handling
• Events are the actions performed by the user in order to interact with
the application, for e.g. pressing a button or touching the screen.
• The events are managed by the android framework in the FIFO
manner i.e. First In – First Out.
• Handling such actions or events by performing the desired task is
called Event Handling.

April 15, 2024 Mobile Application Development - Elias Debelo 52


- onClickListener
• OnClickListener() – This method is called when the user clicks,
touches, or focuses on any view (widget) like Button, ImageButton,
Image, etc.
• Add using xml (onClick attribute)
• Use anonymous callback method in activity context
• Or implement OnClickListener Class

April 15, 2024 Mobile Application Development - Elias Debelo 53


Notification – with Toast
• A toast provides simple feedback about an operation in a small popup. It only fills
the amount of space required for the message and the current activity remains
visible and interactive.
• Toasts automatically disappear after a timeout.
• CharSequence text = "Hello toast!";
• int duration = Toast.LENGTH_SHORT;
• Toast toast = Toast.makeText(this /* MyActivity */, text, duration);
• toast.show();
• Or to avoid holding object;
• Toast.makeText(context, text, duration).show();

April 15, 2024 Mobile Application Development - Elias Debelo 54


Alternatives to using toasts
• If your app is in the foreground, consider using a snackbar instead of
using a toast.
• Snackbars include user-actionable options, which can provide a better
app experience.
• If your app is in the background, and you want users to take some
action, use a notification instead.

April 15, 2024 Mobile Application Development - Elias Debelo 55


Intent – Start Activity
• Start activity
✓Intent intent = new Intent(FirstActity.this, SecondActivity.class);

• Passing Data to Activity


• intent.putExtra("media_id", "a1b2c3");
• startActivity(intent);
• From Receiver side
• Intent intent = getIntent();
• String data = intent.getStringExtra(("media_id");

April 15, 2024 Mobile Application Development - Elias Debelo 56


Intent – using bundle
• Google recommend using bundle for passing data between activities,
it is highly optimized for marshalling and unmarshalling using
parcels.
• Sending
Intent intent = new Intent(FirstActity.this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key", "value");
intent.putExtras(bundle);
startActivity(intent);
• Receiving
Bundle bundle = getIntent().getExtras();
String title = bundle.getString(" key", "Default"); //default: in case key didn’t exist

April 15, 2024 Mobile Application Development - Elias Debelo 57


Menus
• Menus are a common user interface component in many types of
apps. To provide a familiar and consistent user experience.
• Three fundamental types of menus:
• Options menu and app bar - The options menu is the primary collection of menu items for an
activity. It's where you place actions that have a global impact on the app
• Context menu and contextual action mode;
• Floating menu – Appears on long press on an item. It provides actions that affect the selected content or context frame.
• Contextual action mode - displays action items that affect the selected content in a bar at the top of the screen and lets the
user select multiple items
• Popup Menu - A popup menu displays a vertical list of items that's anchored to the view that invokes
the menu
• Define separate res/menu/ directory
• Create menu xml file inside menu directory

April 15, 2024 Mobile Application Development - Elias Debelo 58


Cont.
• In you activity/fragment
• Inflate (convert resource into programmable object) your
menu xml.
• Override onCreateOptionsMenu to inflate menu file
• Override onOptionsItemSelected to handle click event use menu
item id

April 15, 2024 Mobile Application Development - Elias Debelo 59


Dialog
• A dialog is a small window that prompts the user to make a decision or
enter additional information.
• A dialog doesn't fill the screen and is normally used for modal events
that require users to take an action before they can proceed.
• The Dialog class is the base class for dialogs, but don't instantiate
Dialog directly. Instead, use one of the following subclasses:
AlertDialog
A dialog that can show a title, up to three buttons, a list of selectable items, or a
custom layout.
DatePickerDialog or TimePickerDialog
A dialog with a predefined UI that lets the user select a date or time.
April 15, 2024 Mobile Application Development - Elias Debelo 60
Alert dialog
• You can accomplish a wide variety of dialog designs—including custom
layouts and those described in Material Design Dialogs—by extending
DialogFragment and creating an AlertDialog in the onCreateDialog()
callback method.
• Follow this simple steps
• Create Java Class in your package
• Extend DialogFragment
• Use onCreateDialog method, Create AlertDialog.Builder and
• Add message, negative and/or positive button
• Return the dialogname.create()
• In your main class, call object of your DialogFragment with show(manager, Tag)

April 15, 2024 Mobile Application Development - Elias Debelo 61


Working with Data Storage

April 15, 2024 Mobile Application Development - Elias Debelo 62


Shared Preference
• SharedPreferences is best suited to storing data about how the user prefers to
experience the app, for example, whether the user prefers a particular UI theme
or whether they prefer viewing particular content in a list vs. a grid.
• To this end, SharedPreferences reflects changes committed or applied by Editors
immediately, potentially before those changes are durably persisted.
• SharedPreferences is not recommended for storing data that is sensitive to this
kind of rollback to a prior state such as user security or privacy settings.
• SharedPreferences.Editor – is an interface used for modifying values in a
SharedPreferences object. All changes you make in an editor are batched, and not
copied back to the original SharedPreferences until you call commit() or
apply()

April 15, 2024 Mobile Application Development - Elias Debelo 63


Cont.
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
• Then, get Editor
SharedPreferences.Editor editor = sharedPref.edit();
• Write to shared preference
editor.putInt(getString(R.string.saved_high_score_key), newHighScore);
editor.apply();
• Caption: apply() changes the in-memory SharedPreferences object immediately but
writes the updates to disk asynchronously. Alternatively, you can use commit() to write
the data to disk synchronously. But because commit() is synchronous, you should avoid
calling it from your main thread because it could pause your UI rendering.

April 15, 2024 Mobile Application Development - Elias Debelo 64


Cont.
Read from Shared Preference
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);
int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);

Simply, call to sharedPref.getString(“key”, default value);

Using DataStore is recommended by Google instead of SharedPreference.


Yet it is part of Android Jetpack.

April 15, 2024 Mobile Application Development - Elias Debelo 65


Working with SQLite
• Android SQLite is a very lightweight database which comes with Android OS.
Android SQLite combines a clean SQL interface with a very small memory
footprint and decent speed.
• For Android, SQLite is “baked into” the Android runtime, so every Android
application can create its own SQLite databases. Android SQLite native API is
not JDBC, as JDBC might be too much overhead for a memory-limited
smartphone.
• Once a database is created successfully its located in data/data//databases/
accessible from Android Device Monitor.

April 15, 2024 Mobile Application Development - Elias Debelo 66


Cont.
• SQLite is a typical relational database, containing tables (which consists of rows
and columns), indexes etc.
• We can create our own tables to hold the data accordingly. This structure is
referred to as a schema.
• Saving data to a database is ideal for repeating or structured data, such as contact
information.
• Android stores your database in your app's private folder.

April 15, 2024 Mobile Application Development - Elias Debelo 67


Cont.
• Steps
• Create a database using an SQL helper
• The SQLiteOpenHelper class contains a useful set of APIs for managing your database.
When you use this class to obtain references to your database, the system performs the
potentially long-running operations of creating and updating the database only when needed
and not during app startup. All you need to do is call getWritableDatabase() or
getReadableDatabase().
• To access your database, instantiate your subclass of SQLiteOpenHelper:
• For management and simplicity create separate class say DBManager,
DBAdapter...etc.
• A class where to implement operations; write to and read from database.

April 15, 2024 Mobile Application Development - Elias Debelo 68


Cont.
• Using ContentValues from ContentResolver class for setting values.
ContentValues cv = new ContentValues();
cv.putString(“column name”, value);
• Content Providers
• Content providers can help an application manage access to data stored by itself or stored by
other apps and provide a way to share data with other apps.
• They encapsulate the data and provide mechanisms for defining data security.
• Content providers are the standard interface that connects data in one process with code
running in another process.
• Implementing a content provider has many advantages. Most importantly, you can configure
a content provider to let other applications securely access and modify your app data.

April 15, 2024 Mobile Application Development - Elias Debelo 69


Sample Database – NOTES
• Download these two Java files (DBHelper & DBManager) from GitHub Repository.
• DBHelper
• Extends and overrides onCreate, onUpgrade and onDowngrade methods from SQLiteOpenHelper.
• Used to create database schema and tables.
• Database name is db_test.db (because it shall be stored inside app private directories. Check Device
Explorer > data > data > your package > databases)
• DBManager
• Initializes DBHelper Class
• And shall be used for DB operations. Opening and Closing DB, and manipulating table contents.
• E.g., addNotes(String title, String body) inserts a single row into Notes table.

Google recommends using the Room Persistence Library

April 15, 2024 Mobile Application Development - Elias Debelo 70


Cont.
• How to manage the WHERE clause?
• Updating / inserting
1. Create content value and Use proper table name
2. Add Where Clause e.g. String whereClause = "_id = ? AND title = ?";
3. Add Where Arguments e.g. String []whereArgs = {"1", "Note 3"};
• When selecting
• If cursor contains data,
initial index were
set to -1 by default,
moveToNext()
will bring to zero.

April 15, 2024 Mobile Application Development - Elias Debelo 71


Network Communication
• On the World Wide Web, a web service is a standardized method for
propagating messages between client and server applications.
• A web service is a software module that is intended to carry out a specific set of
functions. Web services in cloud computing can be found and invoked over the
network.
• The web service would be able to deliver functionality to the client that invoked the web
service.
• Any software, application, or cloud technology that uses standardized web
protocols (HTTP or HTTPS) to connect, interoperate, and exchange data
messages – commonly XML (Extensible Markup Language) – across the
internet is considered a web service.

April 15, 2024 Mobile Application Development - Elias Debelo 72


Cont.
• XML and HTTP is the most fundamental web services platform. The
following components are used by all typical web services:
oSOAP (Simple Object Access Protocol) - It is a transport-independent
messaging protocol. SOAP is built on sending XML data in the form of SOAP
Messages. A document known as an XML document is attached to each message. Only
the structure of the XML document, not the content, follows a pattern.
oUDDI (Universal Description, Discovery, and Integration) - UDDI is a
standard for specifying, publishing and discovering a service provider’s online services.
It provides a specification that aids in the hosting of data via web services.
UDDI provides a repository where WSDL files can be hosted so that a client application
can discover a WSDL file to learn about the various actions that a web service offers. As a
result, the client application will have full access to the UDDI, which serves as a database
for all WSDL files.

April 15, 2024 Mobile Application Development - Elias Debelo 73


Cont.
▪ WSDL (Web Services Description Language) - If a web service can’t be found, it
can’t be used. The client invoking the web service should be aware of the
location of the web service.
o Second, the client application must understand what the web service does in
order to invoke the correct web service.
o The WSDL, or Web services description language, is used to accomplish this.
The WSDL file is another XML-based file that explains what the web service
does to the client application.
o The client application will be able to understand where the web service is located
and how to use it by using the WSDL document.

April 15, 2024 Mobile Application Development - Elias Debelo 74


HTTP Request - URLConnection
▪ A URLConnection with support for HTTP-specific features.
▪ Uses of this class follow a pattern:
▪ Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to
HttpURLConnection.
▪ Prepare the request. The primary property of a request is its URI. Request headers may also include
metadata such as credentials, preferred content types, and session cookies.
▪ Optionally upload a request body. Instances must be configured with setDoOutput(true) if they
include a request body. Transmit data by writing to the stream returned by
URLConnection.getOutputStream().
▪ Read the response. Response headers typically include metadata such as the response body's content
type and length, modified dates and session cookies. The response body may be read from the stream
returned by URLConnection.getInputStream(). If the response has no body, that method returns an
empty stream.
▪ Disconnect. Once the response body has been read, the HttpURLConnection should be closed by
calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed
or reused.
April 15, 2024 Mobile Application Development - Elias Debelo 75
Cont.
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
Use BufferedReader for buffering and efficient reading
April 15, 2024 Mobile Application Development - Elias Debelo 76
Cont.
▪ Basically, executing long running tasks like this are not recommend of on main
thread (UI thread).
▪ Rather use separate thread.
▪ There are large number of third party packages for dependency injection
utilizing and simplifies the power java connectivity.
▪ But simple operations we may try ExecutorService available APIs.
▪ This service will let you load long task in background and publish to UI on finish
without interrupting UI rendering.

April 15, 2024 Mobile Application Development - Elias Debelo 77


Reading Json
• JSON stands for JavaScript Object Notation
• JSON is a text format for storing and transporting data
• JSON is "self-describing" and easy to understand
• Json Object
• {"name":"John"}
• JavaScript Object
• {name :"John"}
• Json Array => [“John”, “Mike”]
• JSONArray and JSONObject are available in Java.

April 15, 2024 Mobile Application Development - Elias Debelo 78

You might also like