Android Important Notes
Android Important Notes
It includes the visual appearance, the manner of writing, or the way content is arranged.
Types:
1. Writing Style:
Formal: Uses proper language and structure (e.g., academic papers).
Informal: More relaxed and conversational (e.g., blogs, personal letters).
2. Design Style:
Modern: Simple, clean, and sleek with minimal distractions.
Vintage: Uses older designs and colors, sometimes evoking nostalgia.
Themes: A theme refers to the main idea or subject of a piece of content. In design, it's
the overall look and feel. In writing, it's the central message or concept being explored.
Types:
1. In Writing:
Love: The central idea is about romantic relationships (e.g., Romeo and Juliet).
Friendship: The focus is on bonds between people (e.g., Harry Potter).
2. In Design:
Nature: Earthy colors, plants, landscapes.
Retro: Designs that evoke a past era, like the 1980s or 1960s.
Implementing Material Design refers to applying a set of design principles and guidelines
created by Google for user interface (UI) development. Material Design aims to create
visually appealing, functional, and intuitive apps, websites, or systems by using consistent
patterns, layouts, and animations that resemble the physical world (material objects).
Below are the key headings and their explanations:
1. Material Design Basics: Material Design is a design language that uses grid-based
layouts, responsive animations, padding, and depth effects such as lighting and shadows
to create a clean, modern, and consistent user experience.
2. Typography: Typography refers to the style and arrangement of text within an
application or website. Material Design emphasizes using clear, readable fonts for easy
navigation and understanding.
3. Color Palette: Material Design uses a bold and consistent color palette to define
different elements of the UI. The colors are selected to create visual harmony and ensure
good contrast.
4. Layout: Layout in Material Design ensures a structured, balanced, and visually
appealing placement of content on a screen. It focuses on spacing, alignment, and grids.
5. Components: Material Design provides several ready-made UI components that can be
used directly in development to maintain consistency and save time.
Adding an offline cache and repository
1. Offline Cache: Offline cache refers to storing data temporarily on the device so that it
can be accessed when the user is offline (without an internet connection). This is like a
"local storage" where frequently used data is stored for fast retrieval.
Example: In a messaging app, the last few messages you received might be stored in the
cache. So even if you lose internet connectivity, you can still view those messages until
the internet is restored.
Types: 1. Memory Cache: Data is stored temporarily in the RAM (Random Access
Memory) and is cleared when the app is closed or the device is restarted. 2. Disk Cache:
Data is stored on the device's hard drive or storage, and it persists even when the app is
closed.
2. Repository: A repository is a design pattern used to manage the storage and retrieval
of data. It acts as an intermediary between the data source (like a database or web
service) and the rest of the application. In the context of offline functionality, it manages
both the online and offline data sources.
Example: A weather app may retrieve weather data from a server when online, but if the
user goes offline, it will use a local repository that contains cached weather data for offline
access.
Types: 1. Local Repository: A repository that manages the local data storage (like a local
database or file system). 2. Remote Repository: A repository that manages the
communication with remote servers or databases, usually via APIs.
Implementing Work Manager refers to using a software component or system that helps
manage background tasks or work in an application. A Work Manager is typically used to
handle tasks that need to run in the background (such as downloading files, uploading
data, or updating content) and to ensure that these tasks are done properly even if the
app is closed or the device restarts.
Here’s a breakdown of key concepts involved in implementing Work Manager:
1. Work Manager Overview: Work Manager is a library provided by Android (and also
available in other platforms) to schedule, manage, and execute background tasks.
2. Types of Work: Work can be categorized based on how and when it should run:
One-time Work: A task that runs once at a specific time or after a condition is met.
Periodic Work: A task that runs periodically (at regular intervals).
3. Work Request: A request for work to be executed, which specifies the work’s type,
conditions, and constraints.
Working with Background Workers and Periodic Worker Requests When developing
applications, especially in mobile apps or web services, it's important to perform tasks in the
background, so they don’t interrupt the user’s experience. Background workers help with
running these tasks without freezing the main interface. Periodic worker requests are
scheduled tasks that occur at regular intervals to perform certain operations.
1. Background Workers: A background worker is a process that runs behind the scenes in an
application, handling tasks without disturbing the main user interface (UI).
Example: While a user is using a messaging app, the app might be downloading messages in
the background without interrupting the user’s chat experience.
Types of Background Workers:
1. Threading: Allows multiple tasks to run concurrently (e.g., downloading a file while playing
music). 2. Service Workers: In web development, service workers handle background tasks
such as push notifications or caching for offline use.
Example in mobile apps: A photo-editing app might use a background worker to save images
while the user continues to edit others.
2. Periodic Worker Requests: These are tasks scheduled to run repeatedly at specified
intervals, such as sending notifications, syncing data, or checking for updates.
Example: An app that checks for new email every 5 minutes uses a periodic worker to send a
request to the server to check for updates.
Collections are a common concept for most programming languages, so if you're familiar
with, for example, Java or Python collections, you can skip this introduction and proceed to
the detailed sections. A collection usually contains a number of objects of the same type
(and its subtypes). Objects in a collection are called elements or items.
The following collection types are relevant for Kotlin:
List is an ordered collection with access to elements by indices – integer numbers
that reflect their position.
Set is a collection of unique elements. It reflects the mathematical abstraction of set:
a group of objects without repetitions.
Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them
maps to exactly one value.
Connecting to a Web Service with Retrofit Library
Retrofit is a powerful HTTP client for Android and Java, developed by Square. It simplifies
the process of making network requests to RESTful web services.
Here’s a step-by-step guide to connect to a web service using Retrofit in Android with
Kotlin:
1. Add Dependencies:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
2. Create API Interface:
@GET("users/{id}")
Call<User> getUser(@Path("id") String id);
3. Build Retrofit Instance:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
4. Call API:
api.getUser("123").enqueue(new Callback<User>() { ... });
Activity Lifecycle: An activity represents a single screen in an Android app. It goes through
several stages during its lifecycle, such as:
onCreate(): Called when the activity is created.
onStart(): Called when the activity is becoming visible to the user.
onResume(): Called when the activity starts interacting with the user.
onPause(): Called when the activity is no longer in the foreground but still visible.
onStop(): Called when the activity is no longer visible to the user.
onRestart(): Called when the activity is brought back to the foreground after being stopped.
onDestroy(): Called when the activity is about to be destroyed.
Fragment Lifecycle: A fragment is a portion of the user interface that can be reused across
different activities. Its lifecycle is similar to that of an activity but with some additional methods:
onAttach(): Called when the fragment is attached to an activity.
onCreate(): Called when the fragment is created.
onCreateView(): Used to inflate the fragment’s layout.
onActivityCreated(): Called when the activity's onCreate() method has been executed.
onStart(): Called when the fragment is visible to the user.
onResume(): Called when the fragment is interacting with the user.
onPause(): Called when the fragment is no longer in the foreground but still visible.
Android App Architecture: Android App Architecture refers to the design principles,
patterns, and components that guide the development of a well-structured,
maintainable, and scalable Android application.
1. MVC (Model-View-Controller):
Model: Represents data and business logic.
View: Represents the user interface.
Controller: Acts as an intermediary between Model and View.
Example: An old Android app that uses activities as controllers.
2. MVVM (Model-View-ViewModel):
Model: Data layer (usually from a database or API).
View: User interface.
ViewModel: Stores UI-related data and handles business logic, allowing the View
to observe changes in the data.
Example: Google’s Jetpack architecture uses MVVM to simplify UI updates.
3. MVP (Model-View-Presenter):
Model: Data layer.
View: User interface.
Presenter: Acts as an intermediary between Model and View. It handles all the UI
logic and communicates with the Model.
Components of Android Architecture:
Activities and Fragments: Responsible for the UI and user interaction.
Services: Handle background tasks.
Broadcast Receivers: Listen for system or app events (e.g., incoming calls, Wi-Fi changes).
Content Providers: Manage shared data between apps.
ViewModel:
Purpose: Stores and manages UI-related data, ensuring it persists through
configuration changes and is available to the next UI controller instance.
Lifecycle: Its lifecycle is tied to the lifecycle of the UI controller (Activity or Fragment)
but survives configuration changes.
Example: Storing a game score that should remain even if the screen rotates.
ViewModelFactory:
Purpose: Creates instances of ViewModels, especially when the ViewModel
constructor needs dependencies passed in.
Alternative to Default Instantiation: When you cannot directly instantiate a
ViewModel (e.g., it requires dependencies), a ViewModelFactory provides a way to
create instances of the ViewModel with the necessary constructor parameters.
Example: A ViewModel that uses a Repository to fetch data might use a
ViewModelFactory to inject the Repository as a dependency.
Live Data is an observable data holder in Android. It is part of the Android Architecture
Components and is lifecycle-aware, meaning it respects the activity or fragment lifecycle,
and only updates UI components when the activity or fragment is in an active state (e.g.,
when the app is in the foreground). This prevents memory leaks and ensures the app is
efficient. Example: You can use LiveData to store a value like user data or a list of items.
Whenever the data changes, the UI is automatically updated.
Live Data Observers: Observers are responsible for listening to changes in LiveData. When
data changes, the observer automatically gets notified and can update the UI accordingly.
Example: If the user’s profile information changes, the LiveData object stores the updated
data, and an observer in the UI (like an Activity or Fragment) gets notified to update the UI.
In Kotlin, Control flow statements allow you to control the execution of your code based on
conditions or repeatedly execute certain blocks of code. The main control flow statements are:
1. if:- The if statement in Kotlin works similarly to other languagesbut with some enhancements.
It can be used both as a statement and as an expression, meaning it can return a value.
2. when:- when is a more powerful version of the switch statement found in other languages.
3. for:- The for loop in Kotlin is typically used to iterate over ranges, arrays, or collections.
4. while:- The while loop in Kotlin works as expected. It continues to execute a block of code as
long as the condition is true.
5. do-while:- The do-while loop is similar to the while loop, but the condition is checked
after the block of code is executed.
Null safety in Kotlin is a feature that aims to eliminate the risk of null pointer exceptions,
a common issue in programming languages that allow variables to hold null values.
Kotlin introduces a system of nullable and non-nullable types to address this problem.
Nullable Types in Kotlin
In Kotlin, a variable can hold either a non-null value of a certain type or a nullable
value that can also be null.
Nullable types allow variables to hold null values, which can be useful for cases
where absence of value is a valid state.
Non-Nullable Types in Kotlin
Non-nullable types are the default in Kotlin.
Non-nullable types promote better code readability and fewer runtime errors,
making your code more reliable.
Visibility modifiers define the accessibility of classes, methods, and properties. Kotlin has
the
following visibility modifiers:
public: The default modifier; accessible from anywhere.
private: Accessible only within the class.
protected: Accessible in the class and its subclasses.
internal: Accessible within the same module.
Example:
class Car {
private val engine = "V8" // Only accessible within the Car class
fun start() {
println("Engine type: $engine") } }
Interfaces: An interface defines a contract of methods that a class must implement. It’s
similar to a class but can’t have a body for the methods. A class can implement multiple
interfaces.
Example:
interface Drivable
{ fun drive() }
class Car : Drivable {
override fun drive() {
println("Car is driving") } }
val car = Car() car.drive()
// Calls the drive method from Drivable interface
Introduction to Object-Oriented Programming (OOP) in Kotlin:
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and
classes.
In Kotlin, OOP is used to organize and structure code. It makes code more modular,
reusable,
and easier to maintain. OOP principles are based on 4 main concepts: Encapsulation,
Abstraction, Inheritance, and Polymorphism. Example: In Kotlin, classes are blueprints that
define objects. Objects represent instances of these classes.
Default arguments allow you to specify default values for function parameters. If the caller
doesn't provide a value for a parameter, the default value will be used.
Calling Functions with Default Arguments: You can call the function and provide values for
one or both arguments. If you omit any argument, the default value will be used.
Named arguments allow you to explicitly specify which argument corresponds to which
parameter by using the parameter name in the function call. This improves readability,
especially when a function has many parameters.
Calling Functions with Named Arguments: You can call the function with named
arguments to specify only the values you want to provide, in any order.
Enum: A special class that represents a group of constants. It’s useful when you have a
predefined set of values, like days of the week or seasons.
Example:
enum class Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
val today = Day.MONDAY
println(today) // Output: MONDAY
Pairs:
A Pair is a simple class that holds two values. It's often used when you want to return two
related values from a function.
Example:
val pair = Pair("John", 30)
println(pair.first) // John
println(pair.second) // 30
Triples:
A Triple holds three values, similar to a Pair but with one additional value. It's useful when
you need to return three related values.
Example:
val triple = Triple("John", 30, "Engineer")
println(triple.first) // John
println(triple.second) // 30
println(triple.third) // Engineer
Application Components
Definition: Application components are the essential building blocks of an Android application.
They define the functionality of the app and allow it to interact with users and other
applications.
These components are:
1. Activities
Definition: An Activity is a single screen in an Android application. It represents a user interface
(UI) where users can interact with the app.
Example: In a social media app, an Activity could be the screen where you view your news feed
or the screen where you compose a new post.
Types:
Main Activity: The entry point of an app where the app begins when opened.
Sub Activity: Other screens or pages within the app that can be accessed from the main activity.
2. Services
Definition: A Service is a component that runs in the background to perform long-running
operations, like playing music, downloading files, or performing network requests.
Example: If you're downloading a file in the background, the download continues even if you
switch to another app. The service is handling the download.
Types:
Foreground Service: Performs operations that the user is actively aware of (like playing music).
Background Service: Works without direct user interaction (like syncing data).
3. Broadcast Receivers
Definition: Broadcast Receivers are components that listen for system-wide or app-specific
messages (called broadcasts). These broadcasts can be from the Android system or other apps.
Example: A broadcast receiver might listen for changes in network connectivity (e.g., when the
device connects to Wi-Fi) and take action, like notifying the user.
Types:
System Broadcast Receivers: These listen to system-level broadcasts like screen on/off, etc.
Custom Broadcast Receivers: These are used to listen for broadcasts sent by other apps or
within the same app.
4. Content Providers
Definition: A Content Provider allows data from one app to be shared with another app in a
structured manner. They define a way to manage and access data (like contacts, files, or
databases).
Example: If an app wants to access contacts from the phone's contact book, it will use a content
provider to retrieve that data.
Types:
Standard Content Providers: Provided by Android to access common data types.
Custom Content Providers: Created by developers to allow access to custom app data.
Creating Various Layouts Using XML and Layout Editor:- In Android, layouts define the
structure and appearance of user interfaces (UI). Layouts are typically defined using XML
files. Android Studio provides a Layout Editor, which is a visual tool for designing UI, and
also allows you to create layouts directly in XML.
Basic Layout Types in Android:
1. LinearLayout: LinearLayout arranges its child views in a single row or column
(vertically or horizontally).
2. RelativeLayout: RelativeLayout allows you to position UI components relative to
each other or relative to the parent container.
3. FrameLayout: FrameLayout is used to display a single child view. It is generally
used to stack elements or as a container for fragments.
4. ConstraintLayout: ConstraintLayout is a flexible and efficient layout that allows you to
create complex layouts with flat view hierarchies, reducing the need for nested layouts.
Data Binding is a powerful feature in Android that allows you to bind UI components to
data sources (variables, model objects, etc.) in a declarative way. It minimizes boilerplate
code, such as findViewById() and setText() calls. Steps to Use Data Binding:
1. Enable Data Binding in Your Project: In your build.gradle (Module: app) file, enable
data binding by adding the following code inside the android block.
2. Create a Layout with Data Binding: In the layout XML file (activity_main.xml), wrap
your layout with a <layout> tag and define the <data> section at the top to declare
variables that you want to bind.
3. Create a ViewModel: Create a ViewModel class that holds the data to bind to the
UI. The ViewModel will have properties that will be accessed from the layout file.
4. Bind the ViewModel to the Layout in Activity: In your MainActivity, use the
DataBindingUtil to bind the layout to the ViewModel.
Creating Fragments in Android:- A Fragment is a modular section of an Android UI that can
be combined with other fragments to form an activity. Fragments allow you to build more
flexible UIs, especially for devices with larger screens . A fragment represents a portion of
the user interface in an activity, and it can be reused across multiple activities.
Steps to Create and Use a Fragment:
1. Defining a Fragment: To create a fragment, you typically extend the Fragment class and
override methods like onCreateView() to inflate the fragment's layout.
2. Fragment Layout (XML): Create an XML layout file for your fragment. This file will define
the fragment's UI components (e.g., TextViews, Buttons, etc.).
3. Adding the Fragment to an Activity: You can add fragments to your activity dynamically
or statically.
4. Dynamic Fragment Handling: Fragments can also be dynamically added and removed
from an activity based on user interactions or other events.
Navigation Graph:
Purpose: To organize and manage the flow of navigation in an application.
Structure:A graph where each node represents a destination (like a screen or fragment), and the
edges represent the connections or actions between them.
Representation: In Android development, the Navigation Graph is typically represented as an
XML file.
Navigation Paths:
Purpose: To represent the actual routes that a user takes through the application's navigation
graph.
Definition: A sequence of destinations connected by actions, defining the order in which the
user moves through the app.
Example: A user might start on the home screen, navigate to a specific product page, and then
add the product to their cart – this sequence represents a navigation path.