0% found this document useful (0 votes)
2 views

Android

Android is an open-source operating system based on Linux, developed by the Open Handset Alliance led by Google, designed for mobile devices like smartphones and tablets. It features extensive customization, supports various connectivity options, and includes a robust application framework with multiple APIs for developers. The architecture consists of key components such as applications, the Android framework, runtime, platform libraries, and the Linux kernel, facilitating a rich environment for app development.

Uploaded by

shabeadattil2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Android

Android is an open-source operating system based on Linux, developed by the Open Handset Alliance led by Google, designed for mobile devices like smartphones and tablets. It features extensive customization, supports various connectivity options, and includes a robust application framework with multiple APIs for developers. The architecture consists of key components such as applications, the Android framework, runtime, platform libraries, and the Linux kernel, facilitating a rich environment for app development.

Uploaded by

shabeadattil2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

What is Android?

Android is an open-source operating system based on Linux with a Java programming interface
for mvobile devices such as Smartphone (Touch Screen Devices who supports Android OS) as
well for Tablets too.

Android was developed by the Open Handset Alliance (OHA), which is led by Google.
The Open Handset Alliance (OHA) is a consortium of multiple companies like Samsung, Sony,
Intel and many more to provide services and deploy handsets using the android platform.

Android Features
Android is a powerful open-source operating system which provides a lot of great features, those
are

• It’s open-source and we can customize the OS based on our requirements.


• It supports connectivity for GSM, CDMA, WIFI, NFC, Bluetooth, etc. for telephony or
data transfer. It will allow us to make or receive a calls / SMS messages and we can send
or retrieve data across mobile networks
• By using WIFI technology we can pair with other devices using apps
• Android has multiple APIs to support location-based services such as GPS
• We can perform all data storage related activities by using lightweight database SQLite.
• It has a wide range of media supports like AVI, MKV, FLV, MPEG4, etc. to play or
record a variety of audio/video and having a different image format like JPEG, PNG,
GIF, BMP, MP3, etc.
• It has extensive support for multimedia hardware control to perform playback or
recording using camera and microphone
• It has an integrated open-source WebKit layout based web browser to support HTML5,
CSS3
• It supports a multi-tasking, we can move from one task window to another and multiple
applications can run simultaneously
• It will give a chance to reuse the application components and the replacement of native
applications.
• We can access the hardware components like Camera, GPS, and Accelerometer
• It has support for 2D/3D Graphics

Android History

Initially, Google launched the first version of Android platform on Nov 5, 2007, from that onwards
Google released a lot of android versions under a codename based on desserts, such as Apple Pie,
Banana Bread, Cupcake, Donut, Éclair, Froyo, Gingerbread, Jellybeans, Kitkat, Lollipop,
marshmallow, etc. and made a lot of changes and additions to the android platform.
Android Architecture
Android architecture is a software stack of components to support mobile device needs. Android
software stack contains a Linux Kernel, collection of c/c++ libraries which are exposed through
an application framework services, runtime, and application.

Following are main components of android architecture those are

1. Applications
2. Android Framework
3. Android Runtime
4. Platform Libraries
5. Linux Kernel

In these components, the Linux Kernel is the main component in android to provide its
operating system functions to mobile and Dalvik Virtual Machine (DVM) which is responsible
for running a mobile application.
Linux Kernel

It is the heart of android architecture that exists at the root of android architecture. Linux kernel is
responsible for device drivers, power management, memory management, device management and
resource access. It manages all the drivers needed during the runtime of an Android device, such
as camera drivers, display drivers, audio drivers, Bluetooth drivers, and memorydrivers, among
others. Among the main features of the Linux kernel are as follows:

• Security: The Linux kernel maintains the security between an application and the host
system.

• Memory Management: It efficiently manages memory, which allows us to develop our


own applications without having to worry about memory allocation.

• Process Management: It effectively manages the workflow process and allocates


resources when required by processes.

• Network Stack: It has the ability to handle network communications effectively and
efficiently.

• Multitasking: One of the main features of Linux is its support for preemptive multitasking.
As a multitasking operating system with asynchronous execution, it enables multiple
processes to share the same processors (CPUs) and other resources one at a time. A CPU
is dedicated to performing just one task at a time.

Platform Libraries
The Library provides the device with a set of instructions that allow it to handle different types of
data in an appropriate way. It is a collection of C/C++ core libraries as well as Java-based libraries,
which support Android development, such as Graphics, Libc, SSL (Secure Socket Layer), SQLite,
Media, Webkit, OpenGL (Open Graphic Library), Surface Manager, etc.
Here are some details about some key Android libraries that are available for Android
development.

• A media library used for playing, recording, and editing audio and video formats.

• A surface manager library that provides display management functionality.

• A collection of OpenGL (Open Graphic Library) and SGL (Scalable Graphics Library),
used for creating 2D and 3D graphics.

• SQLite provides database support, and FreeType provides font support.

• SSL (Secure Socket Layer) provides Internet security and WebKit provides browser
support.
Android Runtime
This section provides a key component called Dalvik Virtual Machine which is a kind of Java
Virtual Machine specially designed and optimized for Android. Android utilizes the DVM to
optimize its battery life, memory usage, and performance. With its special design and optimization,
it can facilitate multiple instances to be run simultaneously on an Android device. In order to
handle threading and low-level memory management, it relies on the Linux kernel.

The Android runtime provides core libraries which let Android application developers develop
Android applications in the Java programming language.

Application Framework
The application framework provides us with Application Programming Interfaces (APIs) and
higher-level services. The Android Application Framework provides classes, interfaces, and
utilities that are used for the development of Android applications.

The Android framework includes the following key services

• Activity Manager − Controls all aspects of the application lifecycle and activity stack.
• Content Providers − Allows applications to publish and share data with other applications.
• Resource Manager: Assists in accessing non-code embedded resources such as strings,
color settings, and layouts for user interfaces.
• Notifications Manager: Allows applications to show alerts and notifications to users via
the user interface of the application.
• View System: It serves as a base class for widgets and handles events.

Applications
Among the layers of the Android architecture, applications are at the top. Applications that come
pre-installed on the device, like contacts, music, app store, cameras, and galleries will be installed
only on this layer. Applications run within Android’s runtime environment, utilizing the classes
and services provided by the application framework. Below are a few examples of some of the
standard applications that come pre-installed on every device:

• SMS client app


• Dialer
• Clock
• App store
• Web browser
• Contact manager
• Calculator
• Music, etc.
Android Emulator
The Android emulator is an Android Virtual Device (AVD), which represents a specific Android device.
An android emulator is used for executing, debugging, and testing android applications. The emulator
helps the developer to run a trial product virtually without an actual hardware device. An emulator is
similar to a physical hardware mobile device including all the features that an actual mobile contains
except that it cannot place an actual phone call. Emulator represents a specific Android device that can
be used as a target platform to run and test your android application on your PC.
Android Foundational Components
An android component is simply a piece of code that has a well defined life cycle. The core
building blocks or fundamental components of android are

• Activities.
• Views.
• Intents.
• Services.
• Content providers.
• Fragments.
• AndroidManifest. xml.

Activities

An activity represents a single screen with a user interface. For example, an email application
might have one activity that shows a list of new emails, another activity to compose an email,
and another activity for reading emails. An activity is implemented as a subclass
of Activity class.

Services

A service is a component that runs in the background to perform long-running operations. For
example, a service might play music in the background while the user is in a different application

Broadcast Receivers

Broadcast Receivers can send or receive messages from other applications or from the system
itself. These messages can be events or intents. For instance, Android system sends broadcasts
when system events occur such as system boots up, device starts charging, connectivity changing,
date changing, low battery.

Content Providers

A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. The data may be stored in the
file system, the database or somewhere else entirely.

View

A View is a simple building block of a user interface. Views are the visual elements that users see
and interact with when using an Android application. It is a small rectangular box that can be
TextView, EditText, or even a button. Views have their properties and methods that allow
developers to customize their appearance and behavior.
Intent
It is an inter-application message passing framework for communication between android
components. The intent describes the “sharing action”.

Fragment
Android Fragment is the part of activity, it is also known as sub-activity. There can be more than
one fragment in an activity. Fragments are used to place two activities on a single activity when
creating the layout of the user interface.

AndroidManifest.xml
Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located
in the root directory of its project hierarchy. The manifest file provides essential information
about your app to the Android operating system,
The Android manifest file helps to declare the permissions that an app must have to access data
from other apps. The Android manifest file also specifies the app’s package name that helps
the Android SDK while building the app. The Android manifest file provides information such as
activities, services, broadcast receivers, and content providers of an android application.

Android Application Structure

Android Studio is the official IDE (Integrated Development Environment) developed by Jet Brains
community which is freely provided by Google for android app development. After completing the setup
of Android Architecture we can create android application in the studio.
The android project contains different types of app modules, source code files, and resource files.
1. Manifests Folder
2. Java Folder
3. res (Resources) Folder
Drawable Folder
Layout Folder
Mipmap Folder
Values Folder
4. Gradle Scripts
Manifests Folder
Manifests folder contains AndroidManifest.xml for our creating the android application. This file contains
information about our application such as application components. It acts as an intermediate between
android OS and our application.
Java folder
Java folder contains all the java source code (.java) files that we create during the app development,
including other Test files. If we create any new project using Java, by default the class files
MainActivity.java file will create automatically under the package name.
Resource (res) folder
The resource folder is the most important folder because it contains all the non code sources like images,
XML layouts, UI strings for our android application.
Res/drawable folder
It contains the different types of images used for the development of the application. We need to add all
the images in a drawable folder for the application development.
Res/layout folder
The layout folder contains all XML layout files which we used to define the user interface of our
application. It contains the activity_main.xml file.
Res/mipmap folder
This folder contains launcher.xml files to define icons that are used to show on the home screen. It
contains different density types of icons depending upon the size of the device such as hdpi, mdpi, xhdpi.
Res/values folder
Values folder contains a number of XML files like strings, dimensions, colors and styles definitions. One of
the most important file is strings.xml file which contains the resources.
Gradle Scripts folder
Gradle means automated build system and it contains number of files which are used to define a build
configuration which can be apply to all modules in our application.

Android SDK

The Android Software Development Kit (SDK) provides you with the API libraries and developer
tools necessary to build, test, and debug apps for the Android platform. It is one of the most
popular SDKs used for Android.
Android SDK is a collection of libraries and Software Development tools that are essential for
Developing Android Applications. Android SDK consists of some tools which are very essential for
the development of Android Application. Android SDK is compatible with all operating systems
such as Windows, Linux, macOS, etc.
Components of Android SDK
Android SDK Components play a major role in the Development of Android applications. Below
are the important components:
Android SDK Tools
Android SDK tool is an important component of Android SDK. It consists of a complete set of
development and debugging tools.
Android SDK Build-Tools
The main functions of Android SDK Build tools are built, debug, run and test Android applications.
Android Emulator
An Android Emulator is a device that simulates an Android device on your system. In Android
Emulator the virtual android device is shown on our system on which we run the Android
application that we code. Thus, it simply means that without needing any physical device Android
SDK component “Android Emulator” provides a virtual device on the System where we run our
Application. The emulator’s come with the configuration for Various android phones, tablets,
Wear OS, and Android TV devices.
Android SDK Platform-tools
Android SDK Platform-tools is helpful when we are working on Project and they will show the
error messages at the same time.
Android SDK Tools
Android SDK tool is a component of SDK tool. It contains the complete set of Debugging and
Development tools for android.

Application life Cycle


The Android application lifecycle is the series of states an app goes
through from when it starts to when it stops:
• Create: The initial stage of the app development life cycle
• Start: The activity is visible to the user
• Resume: The activity is running at the top of the screen and the user is
interacting with it
• Pause: The activity is paused
• Stop: The activity is stopped
• Destroy: The activity is completely destroyed and the system reclaims its
resources

Lifecycle is a process that tells us about the Events performed on an


Activity/Fragment. The Lifecycle is a class/interface which holds the
information about the state of an activity/fragment and also it allows other
objects to observe this state by keeping track of it. Event and State are
used to determine the lifecycle. Each event has its own state.

Here are some of the core lifecycle methods:


• onCreate() Called when the activity is first created

• onStart() Invoked when the activity is visible to the user

• onResume() Called when the activity is running at the top of the screen
and the user is interacting with it

• onPause() Called when the activity is paused

• onStop() Called when the activity is stopped

• onDestroy() Called before the activity is completely destroyed


Android Resources
In Android, almost everything is a resource. Resources are the additional files and static content that your
code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more.
An android component is simply a piece of code that has a well defined life cycle.

Layout

Android Layout is used to define the user interface that holds the UI controls or widgets that will appear
on the screen of an android application or activity screen. Generally, every application is a combination
of View and View Group. So, each activity contains multiple user interface components and those
components are the instances of the View and View Group. All the elements in a layout are built using a
hierarchy of View and View Group objects.
String Resource
A string resource provides text strings for your application with optional text styling and formatting. There are three
types of resources that can provide your application with strings:

String
XML resource that provides a single string.

String Array
XML resource that provides an array of strings.

Quantity Strings (Plurals)


XML resource that carries different strings for pluralization.

String
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).

syntax:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string
name="string_name"
>text_string</string>
</resources>

Example

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="hello">Hello!</string>
<string name="submit_label">Submit</string>
</resources>

String array
syntax:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string-array
name="string_array_name">
<item
>text_string</item>
</string-array>
</resources>

Example
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
</string-array>
</resources>
Javacode
Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);

Quantity strings (plurals)


Different languages have different rules for grammatical agreement with quantity. In English, for example,
the quantity 1 is a special case. We write "1 book", but for any other quantity we'd write "n books". This
distinction between singular and plural is very common, but other languages make finer distinctions. The
full set supported by Android is zero, one, two, few, many, and other.

Android provides you with methods such as getQuantityString() to select the appropriate resource for you.

syntax:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<plurals
name="plural_name">
<item
quantity=["zero" | "one" | "two" | "few" | "many" | "other"]
>text_string</item>
</plurals>
</resources>

Example

<?xml version="1.0" encoding="utf-8"?>


<resources>
<plurals name="numberOfSongsAvailable">
<item quantity="one">%d song found.</item>
<item quantity="other">%d songs found.</item>
</plurals>
</resources>

Javacode

int count = getNumberOfSongsAvailable();


Resources res = getResources();
String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable,
count, count);

When using the getQuantityString() method, you need to pass the count twice if your string includes string
formatting with a number. For example, for the string %d songs found, the first count parameter selects the
appropriate plural string and the second count parameter is inserted into the %d placeholder. If your plural
strings do not include string formatting, you don't need to pass the third parameter to getQuantityString.

Referencing an App Resource


We can access the resource in either our Java code or our XML layouts at any time. To access, the resource
in the XML Layout file, simply use the @ syntax used to access any resource:

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/submit_label" />

To access the resource directly in your Java code, simply use


the getResources.getString or getString methods to access the value given the resource id:

String submitText = getResources().getString(R.string.submit_label)

Color Resources
Colors should be defined within res/values/colors.xml and the XML file looks like the following:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<color name="white">#FFFFFF</color>
<color name="yellow">#FFFF00</color>
<color name="fuchsia">#FF00FF</color>
</resources>

The colors can be accessed in Java code with:

int color = ContextCompat.getColor(context, R.color.yellow);

Referenced within any view in the XML using:

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@color/yellow"
android:text="Hello"/>

Dimension Resources

Dimensions file is used to define all size dimensions used within an app. A dimension is specified
with a number followed by a unit of measure. For example: 10px, 5sp. Dimensions should be
defined within res/values/dimens.xml and the XML file looks like the following:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<dimen name="textview_height">25dp</dimen>
<dimen name="textview_width">150dp</dimen>
<dimen name="ball_radius">30dp</dimen>
<dimen name="font_size">16sp</dimen>
</resources>

The dimensions can be accessed with java


Resources res = getResources();
float fontSize = res.getDimension(R.dimen.font_size);

Referenced within any view in the XML layouts using:

<TextView
android:layout_height="@dimen/textview_height"
android:layout_width="@dimen/textview_width"
android:textSize="@dimen/font_size"/>

User Interface (UI) Design in Android

User Interface (UI) design in Android is a graphical representation of views displayed on a Smartphone or
tablet. It allows users to interact with the features, functions, and contents of the application. Every
application has a user interface with which users can interact. Android provides various pre-built UI
components that allow you to build a GUI for your application. Android also provides other UI modules
for special interfaces, such as dialogues, notifications, menu, etc.

Following are the commonly used UI or input controls in android applications.

• TextView
• EditText
• Button
• ImageButton
• ToggleButton
• CheckBox
• RadioButton
• RadioGroup
• ProgressBar
• Spinner
• TimePicker
• DatePicker
• AlertDialog

1. TextView

In android, TextView is a user interface control that is used to set and display the text. The TextView
control won’t allow users to edit the text.

TextView Attributes
The following are some of the commonly used attributes related to TextView control in android
applications.

Attribute Description

android: id It is used to uniquely identify the control

android:autoLink It will automatically found and convert URLs and email addresses as
clickable links.

android: ems It is used to make the textview be exactly this many ems wide.

android:hint It is used to display the hint text when text is empty

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

android:text It is used to display the text.

android:textColor It is used to change the color of the text.

android:gravity It is used to specify how to align the text by the view's x and y-axis.

android:maxWidth It is used to make the TextView be at most this many pixels wide.

android:minWidth It is used to make the TextView be at least this many pixels wide.

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:textAllCaps It is used to present the text in all CAPS

android:typeface It is used to specify the Typeface (normal, sans, serif, monospace) for the
text.

android:textColorHighlight It is used to change the color of text selection highlight.

android:textColorLink It is used to change the text color of links.

android:fontFamily It is used to specify the fontFamily for the text.

We can create a TextView instance by declaring it inside a layout(XML file) or by instantiating it


programmatically(Java Class).

<TextView android:id="@+id/studname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Your Name " />
TextView code in JAVA

TextView textView = (TextView) findViewById(R.id.textView);


textView.setText("Enter Your Name"); //set text for text view

2. EditText

In android, EditText is a user interface control which is used to allow the user to enter or modify the
text. While using EditText control in our android applications, we need to specify the type of data the
text field can accept using the inputType attribute.

Attributes Description

android:id It is used to uniquely identify the element

android:width It is used to set the width of EditText in pixels

android:hight It is used to set the height of EditText in pixels

android:text It is used to set the text value inside the EditText

android:inputType It is used to mention what type of value should pass in EditText, like
plain text, email, password, etc

android:hint It is used to highlight what should be input when text is empty

android:gravity gravity is used to align the text like left, right, center, top

android:textSize It is used to specify the size of the text

android:textStyle It is used to set the text style like bold, italic, bold italic, etc.

android:textColor It is used to set the color of the text

android:background It is used to set the background of your EditText

android:maxWidth It is used to set the maximum width of View in pixel

android:minWidth It is used to set the minimum width of View in pixel

EditText code in XML

<EditText
android:id="@+id/age"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>

Below is the example code of EditText in which we retrieve the value from a EditText in Java class.

EditText simpleEditText = (EditText) findViewById(R.id.simpleEditText);


String editTextValue = simpleEditText.getText().toString();

3. Button

In android, Button is a user interface control that is used to perform an action whenever the user clicks or
tap on it. Generally, Buttons in android will contain a text or an icon or both and perform an action when
the user touches it. In android, we have a different type of buttons available to use based on our
requirements, those are ImageButton, ToggleButton, RadioButton.

Generally, whenever the user clicks on a Button, the Button object will receives an on-click event. We can
define click event handler for button by adding android:onClick attribute to the <Button> element in our
XML layout file.
Android Button Control Attributes
Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for button control.

android:drawableBottom It’s drawable to be drawn to the below of text.

android:drawableRight It’s drawable to be drawn to the right of text.

android:drawableLeft It’s drawable to be drawn to the left of the text.


Button code in XML:

<Button
android:id="@+id/btOK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"/>

Java Code

Button button = (Button) findViewById(R.id.simpleButton);


button.setText("ok");//set the text on button

4. CheckBox

In android, CheckBox is a two-states button that can be either checked (ON) or unchecked (OFF)
and it will allow users to toggle between the two states (ON / OFF) based on the requirements.
Generally, we can use multiple CheckBox controls in android application to allow users to select one
or more options from the set of values.

By default, the android CheckBox will be in the OFF (Unchecked) state. We can change the default
state of CheckBox by using android:checked attribute.

Generally, whenever the user clicks on CheckBox to Select or Deselect the CheckBox object will
receive an on-click event.

Check box in XML

<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Java" />

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of checkbox

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text for a checkbox.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for checkbox control.

android:padding It is used to set the padding from left, right, top and bottom.

android:onClick It’s the name of the method to invoke when the checkbox clicked.

android:visibility It is used to control the visibility of control.

5. RadioButton

In android, Radio Button is a two-states button that can be either checked or unchecked. The user
can press or click on the radio button to make it select. Generally, we can
use RadioButton controls in an android application to allow users to select only one option from
the set of values.
In android, we use radio buttons with in a RadioGroup to combine multiple radio buttons into one
group and it will make sure that users can select only one option from the group of multiple options.
By default, the android RadioButton will be in OFF (Unchecked) state. We can change the
default state of RadioButton by using android:checked attribute.
RadioButton in XML
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>

Android RadioButton Control Attributes

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of radio button

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text for the radio button.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for radio button control.

android:onClick It’s the name of the method to invoke when the radio button clicked.

android:visibility It is used to control the visibility of control.

6. Spinner

Spinner is a view similar to the dropdown list which is used to select one option from the list of
options.

It provides an easy way to select one item from the list of items and it shows a dropdown list of all
values when we click on it.

By default, the android spinner will show its currently selected value and by using Adapter we can
bind the items to spinner objects.
Spinner in XML

<Spinner android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

To populate spinner with list of values, we need to specify spinner adapter, such as
an ArrayAdapter in activity file

7. TimePicker

In android, TimePicker is a widget for selecting the time of day, in either 24-hour or AM/PM mode.
If we use TimePicker in our application, it will ensure that the users will select a valid time for the day.
Generally, in android TimePicker available in two modes, one is to show the time in clock mode and
another one is to show the time in spinner mode.

DatePicker in XML

<TimePicker android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Following is the example of showing the TimePicker in Clock mode.

<TimePicker android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="clock" />
Following is the example of showing the TimePicker in spinner mode.

<TimePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"/>

Android TimePicker Control Attributes


Attribute Description

android:id It is used to uniquely identify the control

android:timePickerMode It is used to specify timepicker mode, either spinner or clock

android:background It is used to set the background color for the date picker.

android:padding It is used to set the padding for left, right, top or bottom of the date picker.

8. DatePicker

In android, DatePicker is a control that will allow users to select the date by a day, month and year in our
application user interface. Generally, in android DatePicker available in two modes, one is to show the
complete calendar and another one is to show the dates in spinner view.

DatePicker in XML
<DatePicker android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

DatePicker in Calendar mode

<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="calendar"/>

DatePicker with Spinner Mode


<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"/>
DatePicker Control Attributes
Attribute Description

android:id It is used to uniquely identify the control

android:datePickerMode It is used to specify datepicker mode either spinner or calendar

android:background It is used to set the background color for the date picker.

android:padding It is used to set the padding for left, right, top or bottom of the date picker.

9. AlertDialog

In android, Dialog is a small window that prompts messages to the user to make a decision or enter
additional details. Following is the pictorial representation of using dialogs in android applications.

AlertDialog Methods
Method Description

setTitle() It is used to set the title of alertdialog and its an optional component.

setIcon() It is used to set the icon before the title

setMessage() It is used to set the message required message to display in alertdialog.

setCancelable() It is used to allow users to cancel alertdialog by clicking on outside of dialog area by
setting true/false.

setPositiveButton() It is used to set the positive button for alertdialog and we can implement click event
of a positive button.

setNegativeButton() It is used to set the negative button for alertdialog and we can implement click event
of a negative button.

setNeutralButton() It is used to set the neutral button for alertdialog and we can implement click event
of a neutral button.
Android Toast
In android, Toast is a small popup notification that is used to display information about the
operation which we performed in our app. The Toast will show the message for a small period of
time and it will disappear automatically after a timeout.
In android, we can create a Toast by instantiating an android.widget.Toast object
using makeText() method. The makeText() method will take three parameters: application
context, text message and the duration for the toast. We can display the Toast notification by
using show () method.
Following is the syntax of creating a Toast in android applications.
Toast.makeText(context, "message", duration).show();

Android Content Providers


A content provider component supplies data from one application to others on request. A content
provider manages access to a central repository of data. Content Providers act as a medium for
various applications to communicate with each other. A content provider can use different ways
to store its data and the data can be stored in a database, in files, or even over a network.
Content providers support the four basic operations, normally called CRUD-operations. Android
provides some standard content providers to access contacts, media files, preferences and so on.
When you want to access data in a content provider, you use the ContentResolver object in your
application's Context to communicate with the provider as a client.The provider object receives
data requests from clients, performs the requested action, and returns the results.
Content Provider Working
• UI components in Android applications, such as Activities and Fragments, use
the object CursorLoader to send query requests to the ContentResolver.
• Operations requests (create, read, update, delete, etc) are sent as clients to the
ContentProvider by theContentResolver object.
• The ContentProvider processes the request after receiving it from
ContentResolver and returns the desired outcome.
Methods of Content Provider in Android
• onCreate():-This method is called to initialize the provider whenever a content
provider is created. It is used to set up any required resources, such as database
connections or file storage. Typically, this method ensures that the provider is
ready to handle requests for data access.
• query() :-The query method takes parameters to fetch data from the database.
The data is accessed through a cursor object. This method allows you to
specify which columns to retrieve, conditions for filtering rows, sorting
orders, and more
• insert() :-This method is used to insert a row in the database. It takes a URI
and a set of values as parameters and returns the URI of the newly inserted
row. This method ensures that new data entries are added correctly to the
specified database table.
• update():-This method is used to alter the data fields present in the database.
It takes a URI, a set of values to update, and a selection criteria to specify
which rows to update. This method is essential for modifying existing data in
a controlled manner.
• delete() :-This method is used to delete records from the database. It takes a
URI and a selection criteria to specify which rows to delete. This method helps
in removing data entries that are no longer needed, maintaining the integrity
of the database.
• getType():- It returns the MIME(Multipurpose Internet Mail Extension) type
of the data, which can be used as the content URI. This method helps in
determining the type of data returned, which is useful for clients to understand
the format and handle the data appropriately.
Content URIs in Android
• Content URIs are the query string that is passed to the Content Provider.
• URI means Uniform Resource Identifier.
• Content URI’s are used to identify the various types of data in the Content
Provider.
Structure Content URI
• Prefix -Usually, the prefix is set to content://
• Authority – It contains the name of the Provider.
• Path – It contains the location of the data.
• ID – This is an optional parameter that is used to access specific records.
• content://<authority>/<path>/<optional_id>
Built-in Content Provider

Intent

An Intent in Android is a messaging object used to communicate between different components


of an application or between applications. It enables activities, services, and broadcast receivers to
interact with each other. Intents facilitate various actions such as starting a new activity, sending
data between activities, launching background services, or broadcasting system-wide messages.
Types of Intents in Android
1. Explicit Intent
An explicit intent is used when we want to specify the exact component (activity, service, or
broadcast receiver) that should handle the intent. This is commonly used for communication
within the same application.
e.g
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
2. Implicit Intent
An implicit intent does not specify a specific component but declares an action to be performed.
The Android system determines the best component to handle the request. It is mainly used for
invoking external apps (e.g., opening a web page, sending an email, or sharing content).
Intent intent = new Intent(Intent.ACTION_VIEW, ri.parse("https://www.google.com"));
startActivity(intent);
Common Uses of Intents in Android
Starting an Activity, Starting a Service, Sending Data Between Activities, Broadcasting Messages.

Pending Intent

When an app sends a normal Intent, it executes immediately. However, sometimes, an Intent
needs to be executed later by another component, such as:

• Notification actions (e.g., clicking a notification opens an activity)


• Alarms using AlarmManager
• Broadcast receivers for system events
• Widgets triggering app actions

Types of Data Persistence in Android

SharedPreferences (Key-Value Storage)

• Stores small amounts of key-value data (e.g., user settings, preferences).


• Data is stored in XML format in the app’s private storage.
• Used for storing primitive data types like int, boolean, String, etc.
• Data persists even after the app is closed.

Internal Storage (Private App Files)

• Stores files privately within the app’s internal storage.


• Data is not accessible by other apps.
• Automatically deleted if the app is uninstalled.

External Storage (Public Files)

• Stores files in external storage (SD card or device storage).


• Can be accessed by other apps if permissions are granted.

SQLite Database (Structured Data)

• A lightweight relational database for structured storage.


• Stores data in tables, rows, and columns.
• Useful for complex, structured data with relationships.

SQLite

SQLite is a lightweight, embedded, relational database used in Android to store structured data. It does
not require a server and stores data locally in a .db file. Android provides the SQLiteOpenHelper class
to manage database creation and version management.
Why Use SQLite?
• No server setup required
• Supports SQL queries (SELECT, INSERT, UPDATE, DELETE)
• Efficient and fast for local storage
• Supports transactions and indexing
Menus in Android
Menus in Android provide an easy way for users to interact with an application by selecting different
options. In order to use menu, we should define it in a separate XML file and use that file in our application
based on our requirements.

How to define a menu in the xml file


• First, you should create a new menu folder inside of your project resource folder
(res/menu) to define the menu.
• Add a new XML file (res/menu/file.xml) to build your menu.
• This XML (res/menu/file.xml) file can be given any name that you provide.
Important elements of a menu
• <menu> :- Defines a Menu, which is a container for menu items. A <menu> element
must be the root node for the file, and it can hold one or
more <item> and <group> elements.
• <items>: This element is used to create items in the menu. An <items> element can
contain a nested <menu> element to create a submenu.
• <group>: This element is an optional, invisible container
for <item> elements. <group> allows categorizing menu items so they share properties
such as active state and visibility.
Different Types of Menus
In android, we have a three fundamental type of Menus available to define a set of options
and actions in our android applications.
➢ Options Menu
➢ Context Menu
➢ Popup Menu
Option Menu
Options Menu is a primary collection of menu items for an activity and it is useful to
implement actions that have a global impact on the app, such as Settings, Search, etc.

Context Menu
In android, Context Menu is like a floating menu and that appears when the user
performs a long press or click on an element and it is useful to implement actions that
affect the selected content or context frame.
Popup Menu
A popup menu displays a vertical list of items that's anchored to the view that invokes the
menu.

You might also like