0% found this document useful (0 votes)
8 views53 pages

Android Notes

The document provides an overview of various Android development concepts including Java vs Kotlin, RecyclerView, CardView, Android components, and the MVVM architecture. It discusses the importance of libraries like Android Jetpack and Room for efficient data management and UI binding. Additionally, it covers background processing with WorkManager and the role of ViewModel and LiveData in managing app data and lifecycle awareness.

Uploaded by

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

Android Notes

The document provides an overview of various Android development concepts including Java vs Kotlin, RecyclerView, CardView, Android components, and the MVVM architecture. It discusses the importance of libraries like Android Jetpack and Room for efficient data management and UI binding. Additionally, it covers background processing with WorkManager and the role of ViewModel and LiveData in managing app data and lifecycle awareness.

Uploaded by

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

Java vs Kotlin

Syntax

Null Safety

Extension Functions

Lambda Expressions

Coroutines
Your Choice?

- Project Requirements
- Team Expertise
- Personal Preferences
Java Variables
5
King
In Java, variables are used to
store information that you want
to use later in your program.
Java Variables
25
It's like writing your age on a piece of
paper and putting it in the box.
Java Variables
Java Data Types
Data types are used to define the type of
data that a variable can hold.

Each data type has specific characteristics


and uses.
RecyclerView
RecyclerView makes it easy to efficiently display
large sets of data.

You supply the data and define how each item


looks, and the RecyclerView library dynamically
creates the elements when they're needed.
RecyclerView
As the name implies,
RecyclerView recycles those
individual elements. When an
item scrolls off the screen,
RecyclerView doesn't destroy its
view.

Instead, RecyclerView reuses


the view for new items that
have scrolled onscreen.
RecyclerView
As the name implies,
RecyclerView recycles those
individual elements. When an
item scrolls off the screen,
RecyclerView doesn't destroy its
view.

Instead, RecyclerView reuses


the view for new items that
have scrolled onscreen.
RecyclerView
RecyclerView improves
performance and your app's
responsiveness, and it reduces
power consumption.
Creating RecyclerView

1- The Item Layout: an xml layout representing the layout of a single item in the
recyclerview.

2- RecyclerView: creating a recyclerview in the activity and initializing it.

3- Model Class: representing the data class that acts as a structure for holding
the information for every item of recyclerview.

4- Adapter Class: Holding all methods dealing with recyclerview implementation.


(creating, binding and determining the count of items).

5- View Holder: Holds the references to the views within each item’s layout.
Optimizing view lookups.
CardView
Used to display any sort of data by providing
a rounded corner layout along with a
specific elevation.

CardView can be used for creating items in


listview or inside Recycler View.
Creating CardView App

1- The CardView Item Layout: an xml layout representing the layout of a single
item in the recyclerview.

2- RecyclerView: creating a recyclerview in the activity and initializing it.

3- Model Class: representing the data class that acts as a structure for holding
the information for every item of recyclerview.

4- Adapter Class: Holding all methods dealing with recyclerview implementation.


(creating, binding and determining the count of items).

5- View Holder: Holds the references to the views within each item’s layout.
Optimizing view lookups.
Android Components

Activity Services Broadcast Receivers Content Providers


Represents a single Runs in the background Listen for system-wide Manages access to a
screen with a user to perform long-running announcements or intents structured set of data
interface operations without a
user interface
Services
Runs in the background to perform long-running operations without a user interface.

Types of Services:
1- Foreground
2- Background
3- Bound Services
Services Life Cycle
Broadcast Receivers
Listens for system-wide broadcast events or intents and allows your application to
respond to those events.

When any of these events occur, it brings the application into action by either creating a
status bar notification or performing a task.

Unlike activities, android BroadcastReceiver doesn’t contain any user interface.


Fragments

Fragments in Android are a


bit like these LEGO bricks for
building your app
Fragments

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.
Fragment’s Life Cycle

Each Fragment instance has its own lifecycle. When


a user navigates and interacts with your app, your
fragments transition through various states in their
lifecycle as they are added, removed, and enter or
exit the screen.

The Fragment class includes callback methods that


correspond to each of the changes in a fragment's
lifecycle.

These include onCreate(), onStart(), onResume(),


onPause(), onStop(), and onDestroy().
View Pager

ViewPager is a layout manager that allows the user


to flip left and right through pages of data.

It is mostly found in apps like Youtube, Snapchat


where the user shifts right – left to switch to a screen.
Instead of using activities fragments are used.

It is also used to guide the user through the app


when the user launches the app for the first time.
Android Jetpack
Jetpack is a suite of libraries to help developers follow best practices, reduce boilerplate code, and write code that
works consistently across Android versions and devices so that developers can focus on the code they care about.
Why Android Jetpack?
Android Jetpack helps solve major problems such as managing activity life cycles, configuration changes, and
preventing memory leaks.
Jetpack Components
Android Jetpack components bring together the
existing support library and architecture
components and define them into four categories.

Architecture

User Interface

Foundation

Behavior
findViewById()
Finds the first descendant view with the given ID, the
view itself if the ID matches getId(), or null if the ID is
invalid (< 0) or there is no matching view in the
hierarchy.

Every time we use findViewById() to get reference to a


view, Android system must go through the view
hierarchy and find it at runtime. But what about large
apps with hundreds of views and layouts????

Modern mobiles nowadays, have a refresh rate 60 HZ


per 1 second (1000 milliseconds), so Android system will
create our layout with all its views every 16.667
milliseconds.

What about Mobiles with 90 Hz, 120 Hz, 144 Hz …. ????


Data Binding
The Data Binding Library is a support library that
allows you to bind UI components in your layouts to
data sources in your app using a declarative format
rather than programmatically.

Data binding is the process of integrating views in


an XML layout with data objects. The Data Binding
Library is responsible for generating the classes
required for this procedure.

Using Data binding, a binding object will be created


that contains a reference to each view of a layout,
so the android system will not go and search the
views by their ids again and again….
Why Data Binding?
• You can reduce findViewById calls and enhance your app’s
performance

• Helps get rid of memory leaks or nullPointerExceptions

• Uses declarative layout, which is more adaptable

• Supercharges developer productivity by writing error-free,


shorter, simpler-to-understand, and more maintainable code

• Data and Views are separated from each other

• The compiler verifies types during compile time and displays


errors if and when you attempt to assign the incorrect type to
a variable, thanks to type-safety
The name of the layout we wrapped with
<layout></layout> in activity_main.

Using that, android data binding library will create a


binding object with the name of: ActvityMainBinding
Quadratic equations are algebraic equations that have the form ax²+bx+c=0

Considering this form, the discriminant of a quadratic equation is the value b²-4ac. This value goes inside
the square root of the general quadratic formula and determines the type of solutions that we will have.

When D>0, the quadratic equation has two real roots.


When D<0, the quadratic equation has no real roots.
When D=0, the quadratic equation has a repeated root.

We can understand this better if we remember that the


general quadratic formula, which allows us to solve any
quadratic equation, is the following:
ViewModel is a class that is responsible for
preparing and managing the data for an
Activity or a Fragment. It also handles the
communication of the Activity / Fragment
with the rest of the application.

A ViewModel is always created in


association with a scope (a fragment or an
activity) and will be retained as long as the
scope is alive. E.g. if it is an Activity, until it is
finished.

In other words, this means that a


ViewModel will not be destroyed if its owner
is destroyed for a configuration change
(e.g. rotation).
The ViewModel class is a business logic or
screen level state holder. It exposes state
to the UI and encapsulates related
business logic.

Its principal advantage is that it caches


state and persists it through configuration
changes.

This means that your UI doesn’t have to


fetch data again when navigating
between activities, or following
configuration changes, such as when
rotating the screen.
LiveData is an observable data holder class.
Unlike a regular observable, LiveData is
lifecycle-aware, meaning it respects the
lifecycle of other app components, such as
activities, fragments, or services.

This awareness ensures LiveData only


updates app component observers that are
in an active lifecycle state.
If the lifecycle status is STARTED or RESUMED, LiveData considers an
observer to be in an active state. Only active observers are notified of
lifecycle updates by LiveData.

• It eliminates memory leaks caused by the multiple callbacks that


send results to the UI thread, ensuring that the UI is always up to
date.
Update the Data
• It de-couples tight integration between data, mediator, and the UI
to avoid crashed activities.

• UI components continuously monitor relevant data, and LiveData


manages all these tasks automatically as the relevant lifecycle
status changes.

• If the activity or fragment is recreated due to configuration


changes such as device rotation(Portrait, Landscape), it
immediately receives the latest information from LiveData.

• Extended Live Data wraps system services so that they can be


shared within the app.
SQLite Database is an open-source database
provided in Android which is used to store
data inside the user’s device in the form of a
Text file.

We can perform so many operations on this


data such as adding new data, updating,
reading, and deleting this data.

SQLite is an offline database that is locally


stored in the user’s device and we do not
have to create any connection to connect to
this database.
Room is an ORM, Object Relational Mapping
library. In other words, Room will map our
database objects to Java objects.

Room provides an abstraction layer over


SQLite to allow fluent database access while
harnessing the full power of SQLite.
In the case of SQLite, There is no compile-time
verification of raw SQLite queries. But in Room,
there is SQL validation at compile time.

You need to use lots of boilerplate code to


convert between SQL queries and Java data
objects. But, Room maps our database objects to
Java Object without boilerplate code.

As your schema changes, you need to update


the affected SQL queries manually. Room solves
this problem.

Room is built to work with LiveData and RxJava for


data observation, while SQLite does not.
Room has three main components of Room DB :

• Entity
• Dao
• Database
Entity:
The Entity represents a table within the

E database and has to be annotated with


@Entity.

Each Entity consist of a minimum of one

DAO (Database
Access Object):
D field has to define a primary key.

In Room you use data access


objects to access and
manage your data.
The DAO is the main
component of Room and
includes methodes that offer

D
access to your apps
database it has to be
annotated with @Dao.

DAOs are used instead of


query builders and let you
seperate different
components of your
database e.g. current data
and statistics, which allows Database:
you to easily test your Serves as the database holder an
database. is the main accesspoint to your
relational data.

It has to be annotated with


@Database and extents the
RoomDatabase. It also contains
and returns the Dao (Database
Access Object).
Robot’s Brain

Here’s how MVVM works with our robot:


- Model (Robot’s Brain)
- View (Remote Control)
- View Model (Translator)

Translator
Wave Button
Model-View-ViewModel (ie MVVM) is a template
of a client application architecture, proposed by
John Gossman as an alternative to MVC and MVP
patterns when using Data Binding technology.

Its concept is to separate data presentation logic


from business logic by moving it into particular
class for a clear distinction.
The separate code layers of MVVM are:

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. This layer observes
the ViewModel and does not contain any kind of
application logic.

ViewModel: It exposes those data streams which are


relevant to the View. Moreover, it serves as a link
between the Model and the View.
In this app, we’ll follow the MVVM design pattern
with ROOM database.
Entity: contacts_table






Repository is a class that is mainly used to
manage multiple sources of data.

The repository class isolates the data


sources from the rest of the app and
provides a clean API for data access to the
rest of the app.

the Repository can gather data from


different data sources(different REST APIs,
cache, local database storage) and it
provides this data to the rest of the app.
The purpose of the ViewModel is to acquire and
keep the information that is necessary for an
Activity or a Fragment.

It acts as a link between the Model and the View.


It's responsible for transforming the data from the
Model. It provides data streams to the View.

The Activity or the Fragment should be able to


observe changes in the ViewModel.

ViewModels usually expose this information via


LiveData or Android Data Binding.
Firebase is a powerful and comprehensive platform
developed by Google that offers a wide range of tools
and services for building and managing mobile and
web applications.

Firebase for Android is a popular choice among


developers because it simplifies many aspects of app
development, including authentication, real-time
database management, cloud storage, and more.
WorkManager is the recommended solution for
persistent work. Work is persistent when it remains
scheduled through app restarts and system reboots.

Because most background processing is best


accomplished through persistent work, WorkManager
is the primary recommended API for background
processing.

Work manager simplifies and manages background


tasks in android apps. It allows you to schedule and run
tasks in the background, even when the app is not
currently in the foreground
Work manager offers several advantages, such as:
- handling tasks efficiently
- considering network connectivity
- considering device state
- supporting periodic scheduling
A worker is a class that performs a background task.

Defines the task to be executed and its constraints.


Types of WorkRequest:
- OneTimeWorkRequest
- PeriodicWorkRequest

The central component of managing background


tasks. It is responsible for scheduling and executing
WorkRequest.

You might also like