1. Contents
Core building blocks................................................................................................................................4
Android Architecture ......................................................................................................................5
Actitvity Life Cycle...........................................................................................................................7
DVM ................................................................................................................................................8
Android manifest.xml file...............................................................................................................9
Intent filters ..................................................................................................................................11
R.java file.......................................................................................................................................13
Basic UI widgets ............................................................................................................................15
Android Button .............................................................................................................................15
Android Toast................................................................................................................................15
CheckBox.......................................................................................................................................17
Spinner..........................................................................................................................................17
AutoCompleteTextView................................................................................................................17
DatePicker.....................................................................................................................................18
TimePicker.....................................................................................................................................18
ProgressBar...................................................................................................................................20
Working with view and adaptor .......................................................................................................25
1.Adapter ......................................................................................................................................25
2.Views..........................................................................................................................................28
ScrollView......................................................................................................................................31
WebView.......................................................................................................................................31
SearchView....................................................................................................................................32
TabHost.........................................................................................................................................34
Expandable Listview......................................................................................................................36
Multimedia API .................................................................................................................................37
2.VideoView..................................................................................................................................41
Chapter-2 ..............................................................................................................................................41
1.Data Storage & SQLite....................................................................................................................41
1.Shared Preference .....................................................................................................................41
2.Android file System....................................................................................................................42
Know Your Android Device Partition Size using adb Command ...................................................43
boot...............................................................................................................................................44
2. system...........................................................................................................................................44
recovery ........................................................................................................................................44
data ...............................................................................................................................................44
cache.............................................................................................................................................45
misc...............................................................................................................................................45
sdcard............................................................................................................................................45
sd-ext.............................................................................................................................................45
3.Internal storage..........................................................................................................................46
Writing file........................................................................................................................................46
Reading file......................................................................................................................................46
Writing file........................................................................................................................................47
Reading file......................................................................................................................................47
Content Provider, Intent & Notifications..........................................................................................49
1. Accessing built in content providers.....................................................................................49
Content URIs...................................................................................................................................50
Create Content Provider................................................................................................................50
WHAT IS PARSING?JSON PARSING & XML PARSING?...................................................................51
what is sqlite db?How to provide data base connection using sqlite db. ....................................58
what is the use of sqlite openhelper class in android?explain its unimplement methods? ........61
Web services.................................................................................................................................62
SOAP vs REST Web Services..................................................................................................................62
What is emulator?.........................................................................................................................63
Listview .........................................................................................................................................63
what is camera api in android?.....................................................................................................64
create an application that will display toast on specific interval time(splace screen). ................64
Wallpaper manager class..............................................................................................................65
Explain bluetooth adapter class?with its constant and methods.................................................67
what is content provider?Explain built in content providers with example.................................69
Advantages.......................................................................................................................................70
Wifi manager.................................................................................................................................71
give example to get number of available connections.................................................................73
broadcast receiver in android?explain system broadcast with example?....................................77
create a custom event in broadcast receiver with example.........................................................79
notifaction in android ...................................................................................................................80
3. Canvas...........................................................................................................................................84
Paint class with ondraw method...................................................................................................84
Tween animation ..........................................................................................................................85
frame animation ...........................................................................................................................87
Types of 2D animation..................................................................................................................91
4. Core building blocks
An android component is simply a piece of code that has a well defined life cycle e.g.
Activity, Receiver, Service etc.
The core building blocks or fundamental components of android are activities, views,
intents, services, content providers, fragments and AndroidManifest.xml.
Activity
An activity is a class that represents a single screen. It is like a Frame in AWT.
View
A view is the UI element such as button, label, text field etc. Anything that you see is a view.
Intent
Intent is used to invoke components. It is mainly used to:
Start the service
Launch an activity
Display a web page
Display a list of contacts
Broadcast a message
Dial a phone call etc.
Service
Service is a background process that can run for a long time.
There are two types of services local and remote. Local service is accessed from within the
application whereas remote service is accessed remotely from other applications running on
the same device.
5. Content Provider
Content Providers are used to share data between the applications.
Fragment
Fragments are like parts of activity. An activity can display one or more fragments on the
screen at the same time.
AndroidManifest.xml
It contains informations about activities, content providers, permissions etc. It is like the
web.xml file in Java EE.
Android Virtual Device (AVD)
It is used to test the android application without the need for mobile or tablet etc. It can be
created in different configurations to emulate different types of real devices.
Android Architecture
Android operating system is a stack of software components which is roughly divided into five
sections and four main layers as shown below in the architecture diagram.
Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This provides a level
of abstraction between the device hardware and it contains all the essential hardware drivers like
camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good at such as
networking and a vast array of device drivers, which take the pain out of interfacing to peripheral
hardware.
Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit,
well known library libc, SQLite database which is a useful repository for storage and sharing of
6. application data, libraries to play and record audio and video, SSL libraries responsible for Internet
security etc.
Android Libraries
This category encompasses those Java-based libraries that are specific to Android development.
Examples of libraries in this category include the application framework libraries in addition to those
that facilitate user interface building, graphics drawing and database access. A summary of some key
core Android libraries available to the Android developer is as follows −
android.app − Provides access to the application model and is the cornerstone of all Android
applications.
android.content − Facilitates content access, publishing and messaging between
applications and application components.
android.database − Used to access data published by content providers and includes SQLite
database management classes.
android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.
android.os − Provides applications with access to standard operating system services
including messages, system services and inter-process communication.
android.text − Used to render and manipulate text on a device display.
android.view − The fundamental building blocks of application user interfaces.
android.widget − A rich collection of pre-built user interface components such as buttons,
labels, list views, layout managers, radio buttons etc.
android.webkit − A set of classes intended to allow web-browsing capabilities to be built
into applications.
Having covered the Java-based core libraries in the Android runtime, it is now time to turn our
attention to the C/C++ based libraries contained in this layer of the Android software stack.
Android Runtime
This is the third section of the architecture and available on the second layer from the bottom. This
section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual
Machine specially designed and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multi-threading,
which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its
own process, with its own instance of the Dalvik virtual machine.
The Android runtime also provides a set of core libraries which enable Android application
developers to write Android applications using standard Java programming language.
Application Framework
7. The Application Framework layer provides many higher-level services to applications in the form of
Java classes. Application developers are allowed to make use of these services in their 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 − Provides access to non-code embedded resources such as strings, color
settings and user interface layouts.
Notifications Manager − Allows applications to display alerts and notifications to the user.
View System − An extensible set of views used to create application user interfaces.
Applications
You will find all the Android application at the top layer. You will write your application to be
installed on this layer only. Examples of such applications are Contacts Books, Browser, Games etc.
Actitvity Life Cycle
Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android
Activity is the subclass of ContextThemeWrapper class.
An activity is the single screen in android. It is like window or frame of Java.
By the help of activity, you can place all your UI components or widgets in a single screen.
The 7 lifecycle method of Activity describes how activity will behave at different states.
8. Sr.No Callback & Description
1 onCreate()
This is the first callback and called when the activity is first created.
2 onStart()
This callback is called when the activity becomes visible to the user.
3 onResume()
This is called when the user starts interacting with the application.
4 onPause()
The paused activity does not receive user input and cannot execute any code and called
when the current activity is being paused and the previous activity is being resumed.
5 onStop()
This callback is called when the activity is no longer visible.
6 onDestroy()
This callback is called before the activity is destroyed by the system.
7 onRestart()
This callback is called when the activity restarts after stopping it.
DVM
As we know the modern JVM is high performance and provides excellent memory management. But
it needs to be optimized for low-powered handheld devices as well.
The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile devices. It
optimizes the virtual machine for memory, battery life and performance.
Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple class
files are converted into one dex file.
Let's see the compiling and packaging process from the source file:
9. The javac tool compiles the java source file into the class file.
The dx tool takes all the class files of your application and generates a single .dex file. It is a
platform-specific tool.
The Android Assets Packaging Tool (aapt) handles the packaging process.
Android manifest.xml file
Every application must have an AndroidManifest.xml file (with precisely that name) in its root
directory. The manifest file provides essential information about your app to the Android system,
which the system must have before it can run any of the app's code.
Among other things, the manifest file does the following:
It names the Java package for the application. The package name serves as a unique identifier
for the application.
It describes the components of the application, which include the activities, services,
broadcast receivers, and content providers that compose the application. It also names the
classes that implement each of the components and publishes their capabilities, such as the
Intent messages that they can handle. These declarations inform the Android system of the
components and the conditions in which they can be launched.
It determines the processes that host the application components.
It declares the permissions that the application must have in order to access protected parts of
the API and interact with other applications. It also declares the permissions that others are
required to have in order to interact with the application's components.
It lists the Instrumentation classes that provide profiling and other information as the
application runs. These declarations are present in the manifest only while the application is
being developed and are removed before the application is published.
It declares the minimum level of the Android API that the application requires.
It lists the libraries that the application must be linked against.
10. Manifest file structure
The code snippet below shows the general structure of the manifest file and every element that it can
contain. Each element, along with all of its attributes, is fully documented in a separate file.
The following list contains all of the elements that can appear in the manifest file, in alphabetical
order:
<action>
<activity>
<activity-alias>
<application>
<category>
<data>
<grant-uri-permission>
<instrumentation>
<intent-filter>
<manifest>
<meta-data>
<permission>
<permission-group>
<permission-tree>
<provider>
<receiver>
<service>
<supports-screens>
<uses-configuration>
<uses-feature>
<uses-library>
<uses-permission>
<uses-sdk>
File conventions
Elements
Only the <manifest> and <application> elements are required. They each must be present and can
occur only once. Most of the other elements can occur many times or not at all. However, at least
some of them must be present before the manifest file becomes useful.
If an element contains anything at all, it contains other elements. All of the values are set through
attributes, not as character data within an element.
Elements at the same level are generally not ordered. For example, the <activity>, <provider>, and
<service> elements can be intermixed in any sequence. There are two key exceptions to this rule:
An <activity-alias> element must follow the <activity> for which it is an alias.
11. The <application> element must be the last element inside the <manifest> element. In other
words, the </application> closing tag must appear immediately before the </manifest>
closing tag.
Attributes
In a formal sense, all attributes are optional. However, there are some attributes that must be
specified so that an element can accomplish its purpose. Use the documentation as a guide. For truly
optional attributes, it mentions a default value or states what happens in the absence of a
specification.
Except for some attributes of the root <manifest> element, all attribute names begin with an
android: prefix. For example, android:alwaysRetainTaskState. Because the prefix is universal, the
documentation generally omits it when referring to attributes by name.
Declaring class names
Many elements correspond to Java objects, including elements for the application itself (the
<application> element) and its principal components: activities (<activity>), services (<service>),
broadcast receivers (<receiver>), and content providers (<provider>).
If you define a subclass, as you almost always would for the component classes (Activity, Service,
BroadcastReceiver, and ContentProvider), the subclass is declared through a name attribute. The
name must include the full package designation.
Multiple values
If more than one value can be specified, the element is almost always repeated, rather than multiple
values being listed within a single element.
Resource values
Some attributes have values that can be displayed to users, such as a label and an icon for an
activity. The values of these attributes should be localized and set from a resource or theme.
String values
Where an attribute value is a string, you must use double backslashes () to escape characters, such
as n for a newline or uxxxx for a Unicode character.
File features
Intent filters
The core components of an application, such as its activities, services, and broadcast receivers, are
activated by intents. An intent is a bundle of information (an Intent object) describing a desired action,
including the data to be acted upon, the category of component that should perform the action, and
other pertinent instructions. The Android system locates an appropriate component that can respond to
the intent, launches a new instance of the component if one is needed, and passes it the Intent object.
12. The components advertise the types of intents that they can respond to through intent filters. Since the
Android system must learn the intents that a component can handle before it launches the component,
intent filters are specified in the manifest as <intent-filter> elements. A component can have any
number of filters, each one describing a different capability.
An intent that explicitly names a target component activates that component, so the filter doesn't play
a role. An intent that doesn't specify a target by name can activate a component only if it can pass
through one of the component's filters.
For information about how Intent objects are tested against intent filters, see the Intents and Intent
Filters document.
Icons and labels
A number of elements have icon and label attributes for a small icon and a text label that can be
displayed to users. Some also have a description attribute for longer, explanatory text that can also be
shown on-screen. For example, the <permission> element has all three of these attributes so that when
the user is asked whether to grant the permission to an application that has requested it, an icon
representing the permission, the name of the permission, and a description of what it entails are all
presented to the user.
In every case, the icon and label that are set in a containing element become the default icon and label
settings for all of the container's subelements. Thus, the icon and label that are set in the <application>
element are the default icon and label for each of the application's components. Similarly, the icon and
label that are set for a component, such as an <activity> element, are the default settings for each of
the component's <intent-filter> elements. If an <application> element sets a label, but an activity and
its intent filter do not, the application label is treated as the label for both the activity and the intent
filter.
Permissions
A permission is a restriction that limits access to a part of the code or to data on the device. The
limitation is imposed to protect critical data and code that could be misused to distort or damage the
user experience.
Each permission is identified by a unique label. Often the label indicates the action that's restricted.
Here are some permissions that are defined by Android:
android.permission.CALL_EMERGENCY_NUMBERS
android.permission.READ_OWNER_DATA
android.permission.SET_WALLPAPER
android.permission.DEVICE_POWER
A feature can be protected by only one permission.
If an application needs access to a feature that is protected by a permission, it must declare that it
requires the permission with a <uses-permission> element in the manifest. When the application is
installed on the device, the installer determines whether to grant the requested permission by checking
13. the authorities that signed the application's certificates and, in some cases, asking the user. If the
permission is granted, the application is able to use the protected features. If not, its attempts to access
those features fail without any notification to the user.
An application can also protect its own components with permissions. It can employ any of the
permissions that are defined by Android, as listed in android.Manifest.permission, or declared by
other applications. It can also define its own. A new permission is declared with the <permission>
element. For example, an activity could be protected as follows:
<manifest . . . >
<permission android:name="com.example.project.DEBIT_ACCT" . . . />
<uses-permission android:name="com.example.project.DEBIT_ACCT" />
. . .
<application . . .>
<activity android:name="com.example.project.FreneticActivity"
android:permission="com.example.project.DEBIT_ACCT"
. . . >
. . .
</activity>
</application>
</manifest>
Note that, in this example, the DEBIT_ACCT permission is not only declared with the <permission>
element, its use is also requested with the <uses-permission> element.
The <permission-tree> element declares a namespace for a group of permissions that are defined in
code, and the <permission-group> defines a label for a set of permissions, both those declared in the
manifest with <permission> elements and those declared elsewhere. This affects only how the
permissions are grouped when presented to the user. The <permission-group> element does not
specify the permissions that belong to the group, but it gives the group a name. You can place a
permission in the group by assigning the group name to the <permission> element's permissionGroup
attribute.
Libraries
Every application is linked against the default Android library, which includes the basic packages for
building applications (with common classes such as Activity, Service, Intent, View, Button,
Application, and ContentProvider).
However, some packages reside in their own libraries. If your application uses code from any of these
packages, it must explicitly ask to be linked against them. The manifest must contain a separate
<uses-library> element to name each of the libraries. You can find the library name in the
documentation for the package.
R.java file
Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains
resource IDs for all the resources of res/ directory.
14. If you create any component in the activity_main.xml file, id for the corresponding component is
automatically created in this file. This id can be used in the activity source file to perform any action
on the component.
NOTE: IF YOU DELETE R.JAR FILE, ANDROID CREATES IT AUTOMATICALLY.
Let's see the android R.java file. It includes a lot of static nested classes such as menu, id, layout, attr,
drawable, string etc.
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int menu_settings=0x7f070000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int activity_main=0x7f060000;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int hello_world=0x7f040001;
public static final int menu_settings=0x7f040002;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
15. Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
}
}
Basic UI widgets
There are given a lot of android widgets with simplified examples such as Button, EditText,
AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar etc.
Android widgets are easy to learn. The widely used android widgets with examples are given below:
Android Button
In Android, Button represents a push button. A Push buttons can be clicked, or pressed by the user to
perform an action. There are different types of buttons used in android such as CompoundButton,
ToggleButton, RadioButton.
Button is a subclass of TextViewclass and compound button is the subclass of Button class. On a
button we can perform different actions or events like click event, pressed event, touch event etc.
Android buttons are GUI components which are sensible to taps (clicks) by the user. When the user
taps/clicks on button in an Android app, the app can respond to the click/tap. These buttons can be
divided into two categories: the first is Buttons with text on, and second is buttons with an image on.
A button with images on can contain both an image and a text. Android buttons with images on are
also called ImageButton.
Attributes of Button in Android:
1. id:
2. gravity:The gravity attribute is an optional attribute which is used to control the alignment
of the text like left, right, center, top, bottom, center_vertical, center_horizontal etc.
3. text: text attribute is used to set the text in a Button. We can set the text in xml as well as in
the java class.
4. textSize:
5. textStyle:
Android Toast
Andorid Toast can be used to display information for the short period of time. A toast contains
message to be displayed quickly and disappears after sometime.
The android.widget.Toast class is the subclass of java.lang.Object class.
16. You can also create custom toast as well for example toast displaying image. You can visit next page
to see the code for custom toast.
Toast class
Toast class is used to show notification for a particular interval of time. After sometime it disappears.
It doesn't block the user interaction.
Constants of Toast class
There are only 2 constants of Toast class which are given below.
Constant Description
public static final int LENGTH_LONG displays view for the long duration of time.
public static final int LENGTH_SHORT displays view for the short duration of time.
Methods of Toast class
The widely used methods of Toast class are given below.
Method Description
public static Toast makeText(Context context,
CharSequence text, int duration)
makes the toast containing text and
duration.
public void show() displays toast.
public void setMargin (float horizontalMargin, float
verticalMargin)
changes the horizontal and vertical
margin difference.
Custom Toast
You are able to create custom toast in android. So, you can display some images like congratulations
or loss on the toast. It means you are able to customize the toast now.
ToggleButton
Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button.
It is beneficial if user have to change the setting between two states. It can be used to On/Off Sound,
Wifi, Bluetooth etc.
Since Android 4.0, there is another type of toggle button called switch that provides slider control.
Android ToggleButton and Switch both are the subclasses of CompoundButton class.
Android ToggleButton class
ToggleButton class provides the facility of creating the toggle button.
XML Attributes of ToggleButton class
The 3 XML attributes of ToggleButton class.
XML Attribute Description
17. android:disabledAlpha The alpha to apply to the indicator when disabled.
android:textOff The text for the button when it is not checked.
android:textOn The text for the button when it is checked.
Methods of ToggleButton class
The widely used methods of ToggleButton class are given below.
Method Description
CharSequence getTextOff() Returns the text when button is not in the checked state.
CharSequence getTextOn() Returns the text for when button is in the checked state.
void setChecked(boolean checked) Changes the checked state of this button.
CheckBox
Android CheckBox is a type of two state button either checked or unchecked.
There can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the
user, activate/deactivate the specific action etc.
Android CheckBox class is the subclass of CompoundButton class.
Android CheckBox class
The android.widget.CheckBox class provides the facility of creating the CheckBoxes
Methods of CheckBox class
There are many inherited methods of View, TextView, and Button classes in the CheckBox class.
Some of them are as follows:
Method Description
public boolean isChecked() Returns true if it is checked otherwise false.
public void setChecked(boolean status) Changes the state of the CheckBox.
Spinner
Android Spinner is like the combox box of AWT or Swing. It can be used to display the multiple
options to the user in which only one item can be selected by the user.
Android spinner is like the drop down menu with multiple values from which the end user can select
only one value.
Android spinner is associated with AdapterView. So you need to use one of the adapter classes with
spinner.
Android Spinner class is the subclass of AsbSpinner class.
AutoCompleteTextView
Android AutoCompleteTextView completes the word based on the reserved words, so no need to
write all the characters of the word.
18. Android AutoCompleteTextView is a editable text field, it displays a list of suggestions in a drop
down menu from which user can select only one suggestion or value.
Android AutoCompleteTextView is the subclass of EditText class. The MultiAutoCompleteTextView is
the subclass of AutoCompleteTextView class.
DatePicker
In Android, DatePicker is a widget used to select a date. It allows to select date by day, month and
year in your custom UI (user interface). If we need to show this view as a dialog then we have to use
a DatePickerDialog class. For selecting time Android also provides timepicker to select time.
Methods of DatePicker
1. setSpinnersShown(boolean shown):
This method is used to set whether the spinner of the date picker in shown or not. In this
method you have to set a Boolean value either true or false. True indicates spinner is shown,
false value indicates spinner is not shown. Default value for this function is true.
2. getDayOfMonth():
This method is used to get the selected day of the month from a date picker. This method
returns an integer value.
3. getMonth():
This method is used to get the selected month from a date picker. This method returns an
integer value.
4. getYear():
This method is used to get the selected year from a date picker. This method returns an
integer value.
5. getFirstDayOfWeek():
This method is used to get the first day of the week. This method returns an integer value.
Attributes of DatePicker
1. datePickerMode: This attribute is used to set the Date Picker in mode either spinner
or calendar. Default mode is calendar but this mode is not used after api level 21, so
from api level 21 you have to set the mode to spinner.
TimePicker
In Android, TimePicker is a widget used for selecting the time of the day in either AM/PM mode or
24 hours mode. The displayed time consist of hours, minutes and clock format. If we need to show
this view as a Dialog then we have to use a TimePickerDialog class.
19. Methods of TimePicker:
1. setCurrentHour(Integer currentHour):
This method is used to set the current hours in a time picker.
setHour(Integer hour): setCurrentHour() method was deprecated in API level 23. From api
level 23 we have to use setHour(Integer hour). In this method there is only one parameter of
integer type which is used to set the value for hours.
2. setCurrentMinute(Integer currentMinute):
This method is used to set the current minutes in a time picker.
setMinute(Integer minute): setCurrentMinute() method was deprecated in API level 23.
From api level 23 we have to use setMinute(Integer minute). In this method there is only one
parameter of integer type which set the value for minutes.
3. getCurrentHour():
This method is used to get the current hours from a time picker.
getCurrentHour(): getCurrentHour() method was deprecated in API level 23. From api
level 23 you have to use getHour(). This method returns an integer value.
4. getCurrentMinute():
This method is used to get the current minutes from a time picker.
getMinute(): getCurrentMinute() method was deprecated in API level 23. From api level 23
we have to use getMinute(). This method returns an integer value.
5. setIs24HourView(Boolean is24HourView):
This method is used to set the mode of the Time picker either 24 hour mode or AM/PM
mode. In this method we set a Boolean value either true or false. True value indicate 24 hour
mode and false value indicate AM/PM mode.
6. is24HourView():
This method is used to check the current mode of the time picker. This method returns true if
its 24 hour mode or false if AM/PM mode is set.
7. setOnTimeChangedListener(TimePicker.OnTimeChangedListener
onTimeChangedListener):
This method is used to set the callback that indicates the time has been adjusted by the user.
onTimeChanged(TimePicker view, int hourOfDay, int minute) is an override function of this
listener in which we have three parameters first is for TimePicker, second for getting hour of
the day and last is for getting the minutes after changing the time of the time picker.
20. ProgressBar
In Android, ProgressBar is used to display the status of work being done like analyzing status
of work or downloading a file etc. In Android, by default a progress bar will be displayed as a
spinning wheel but If we want it to be displayed as a horizontal bar then we need to use style
attribute as horizontal. It mainly use the “android.widget.ProgressBar” class.
Important Note: A progress bar can also be made indeterminate. In this mode a progress bar
shows a cyclic animation without an indication of progress. This mode is used in application
when we don’t know the amount of work to be done.
To add a progress bar to a layout (xml) file, you can use the <ProgressBar> element. By
default, a progress bar is a spinning wheel (an indeterminate indicator). To change to a
horizontal progress bar, apply the progress bar’s horizontal style.
Methods Used In ProgressBar:
1. getMax() – returns the maximum value of progress bar
We can get the maximum value of the progress bar in java class. This method returns a
integer value. Below is the code to get the maximum value from a Progress bar.
2. getProgress() – returns current progress value
We can get the current progress value from a progress bar in java class. This method also
returns a integer value. Below is the code to get current progress value from a Progress bar.
Attributes of ProgressBar In Android:
1.progress: progress is an attribute used in android to define the default progress value between 0
and max. It must be an integer value.
2.progressDrawable: progress drawable is an attribute used in Android to set the custom
drawable for the progress mode.
Below we set a custom gradient drawable for the progress mode of a progress bar. Before you
try below code make sure to download a progress icon from the web and add in your
drawable folder.
Activity
An activity represents a single screen with a user interface just like window or frame of Java.Android
activity is the subclass of ContextThemeWrapper class.
21. If you have worked with C, C++ or Java programming language then you must have seen that your
program starts from main() function.
Very similar way, Android system initiates its program with in an Activity starting with a call on
onCreate() callback method.
There is a sequence of callback methods that start up an activity and a sequence of callback
methods that tear down an activity.
Android activity lifecycle
The Activity class defines the following call backs i.e. events. You don't need to implement all the
callbacks methods.
However, it's important that you understand each one and implement those that ensure your app
behaves the way users expect.
Sr.No Callback & Description
1 onCreate()
This is the first callback and called when the activity is first created.
2 onStart()
This callback is called when the activity becomes visible to the user.
3 onResume()
This is called when the user starts interacting with the application.
4 onPause()
The paused activity does not receive user input and cannot execute any code and
called when the current activity is being paused and the previous activity is being
resumed.
5 onStop()
This callback is called when the activity is no longer visible.
6 onDestroy()
This callback is called before the activity is destroyed by the system.
7 onRestart()
This callback is called when the activity restarts after stopping it.
Layout
The basic building block for user interface is a View object which is created from the View class and
occupies a rectangular area on the screen and is responsible for drawing and event handling. View is
the base class for widgets, which are used to create interactive UI components like buttons, text
fields, etc.
22. The ViewGroup is a subclass of View and provides invisible container that hold other Views or other
ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical layout
defines the visual structure for an Android user interface and can be created either at run time using
View/ViewGroup objects or you can declare your layout using simple XML file main_layout.xml
which is located in the res/layout folder of your project.
Android Layout Types
There are number of Layouts provided by Android which you will use in almost all the
Android applications to provide different view, look and feel.
Sr.No Layout & Description
1 Linear Layout
LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally.
2 Relative Layout
RelativeLayout is a view group that displays child views in relative positions.
3 Table Layout
TableLayout is a view that groups views into rows and columns.
4 Absolute Layout
AbsoluteLayout enables you to specify the exact location of its children.
5 Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a single view.
6 List View
ListView is a view group that displays a list of scrollable items.
7 Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.
Linear Layout
Linear layout is a simple layout used in android for layout designing. In the Linear layout all the
elements are displayed in linear fashion means all the childs/elements of a linear layout are
displayed according to its orientation. The value for orientation property can be either
horizontal or vertical.
Types Of Linear Layout Orientation
There are two types of linear layout orientation:
1. Vertical:-In this all the child are arranged vertically in a line one after the other.
2. Horizontal:-In this all the child are arranged horizontally in a line one after the other.
As the name specified these two orientations are used to arrange there child one after the other, in
a line, either vertically or horizontally. Let’s we describe these in detail.
23. Relative Layout
The Relative Layout is very flexible layout used in android for custom layout designing. It gives us the
flexibility to position our component/view based on the relative or sibling component’s position. Just
because it allows us to position the component anywhere we want so it is considered as most
flexible layout. For the same reason Relative layout is the most used layout after the Linear Layout in
Android. It allow its child view to position relative to each other or relative to the container or
another container.
Even though Android has drag and drop system to put one component in related to other inside
relative layout. But actually in the background lots of XML properties are working which does this
task. So Android developer can design UI either using drag & drop or using XML code. Professional
developer uses both for designing UI.
Table Layout
In Android, Table Layout is used to arrange the group of views into rows and columns. Table Layout
containers do not display a border line for their columns, rows or cells. A Table will have as many
columns as the row with the most cells.
A table can also leave the cells empty but cells can’t span the columns as they can in
HTML(Hypertext markup language).
Important Points About Table Layout In Android:
For building a row in a table we will use the <TableRow> element. Table row objects are the
child views of a table layout.
Each row of the table has zero or more cells and each cell can hold only one view object like
ImageView, TextView or any other view.
Total width of a table is defined by its parent container
Column can be both stretchable and shrinkable. If shrinkable then the width of column can
be shrunk to fit the table into its parent object and if stretchable then it can expand in width
to fit any extra space available.
Intent
Android application components can connect to other Android applications. This connection is based
on a task description represented by an Intent object.
24. Intents are asynchronous messages which allow application components to request functionality
from other Android components. Intents allow you to interact with components from the same
applications as well as with components contributed by other applications. For example, an activity
can start an external activity for taking a picture.
Intents are objects of the android.content.Intent type. Your code can send them to the Android
system defining the components you are targeting. For example, via the startActivity() method you
can define that the intent should be used to start an activity.
An intent can contain data via a Bundle. This data can be used by the receiving component.
To start an activity, use the method startActivity(intent). This method is defined on the
Context object which Activity extends.
Types of Intents
There are following two types of intents supported by Android
1.Explicit Intents
Explicit intent going to be connected internal world of application,suppose if you wants to connect
one activity to another activity, we can do this quote by explicit intent.
These intents designate the target component by its name and they are typically used for
application-internal messages - such as an activity starting a subordinate service or launching a sister
activity. For example −
// Explicit Intent by specifying its class name
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i);
2.Implicit Intents
These intents do not name a target and the field for the component name is left blank. Implicit
intents are often used to activate components in other applications. For example −
Intent read1=new Intent();
read1.setAction(android.content.Intent.ACTION_VIEW);
read1.setData(ContactsContract.Contacts.CONTENT_URI);
startActivity(read1);
The target component which receives the intent can use the getExtras() method to get the extra
data sent by the source component. For example −
// Get bundle object at appropriate place in your code
25. Bundle extras = getIntent().getExtras();
// Extract data using passed keys
String value1 = extras.getString("Key1");
String value2 = extras.getString("Key2");
Working with view and adaptor
1.Adapter
In Android, Adapter is a bridge between UI component and data source that helps us
to fill data in UI component.
It holds the data and send the data to an Adapter view then view can takes the data
from the adapter view and shows the data on different views like
as ListView, GridView, Spinner etc.
For more customization in Views we uses the base adapter or custom adapters.
To fill data in a list or a grid we need to implement Adapter. Adapters acts like a
bridge between UI component and data source.
Here data source is the source from where we get the data and UI components are
list or grid items in which we want to display that data.
There are the some commonly used Adapter in Android used to fill the data in the UI
components.
1. BaseAdapter – It is parent adapter for all other adapters
2. ArrayAdapter – It is used whenever we have a list of single items which is
backed by an array
3. Custom ArrayAdapter – It is used whenever we need to display a custom list
4. SimpleAdapter – It is an easy adapter to map static data to views defined in
your XML file
5. Custom SimpleAdapter – It is used whenever we need to display a customized
list and needed to access the child items of the list or grid.
ArrayAdapter
In android, An adapter is a bridge between UI component and data source that helps us to
fill data in UI component. It holds the data and send the data to adapter view then view can
takes the data from the adapter view and shows the data on different views
like listview, gridview, spinner etc. ArrayAdapter is more simple and commonly used
Adapter in android.
Whenever you have a list of single type of items which is backed by an array, you can
use ArrayAdapter. For instance, list of phone contacts, countries or names.
26. By default, ArrayAdapter expects a Layout with a single TextView, If you want to use
more complex views means more customization in grid items or list items, please
avoid ArrayAdapter and use custom adapters.
Important Note: ArrayAdapter is an implementation of BaseAdapter so if we need to
create a custom list view or a grid view then we have to create our own custom
adapter and extend ArrayAdapter in that custom class. By doing this we can override all
the function’s of BaseAdapter in our custom adapter.
Parameters used in ArrayAdapter:
Lets discuss parameter in ArrayAdapter class:
context:
The first parameter is used to pass the context means the reference of current class. Here
this is a keyword used to show the current class reference. We can also use
getApplicationContext(), getActivity() in the place of this keyword. getApplicationContext()
is used in a Activity and getActivity() is used in a Fragment.
Below is the example code in which we set the current class reference in a adapter.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, int resource, int textViewResourceId,
T[] objects);
resource:
The second parameter is resource id used to set the layout(xml file) for list items in which
you have a text view.
Below is the example code in which we set the layout.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_view_items, int
textViewResourceId, T[] objects);
textViewResourceId:
The third parameter is textViewResourceId which is used to set the id of TextView where
you want to display the actual text.
Below is the example code in which we set the id(identity) of a text view.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_view_items, R.id.textView,
T[] objects);
objects:
The fourth parameter is an array of objects, used to set the array of elements in the
textView. We can set the object of array or array list here.
27. Below is the example code in which we set the Animal array in adapter to display the Animal
name’s list.
String animalList[] = {"Lion","Tiger","Monkey","Elephant","Dog","Cat","Camel"};
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_view_items, R.id.textView,
animalList);
BaseAdapter
BaseAdapter is a common base class of a general implementation of an
Adapter that can be used in ListView, GridView, Spinner etc.
Whenever you need a customized list in a ListView or customized grids in a
GridView you create your own adapter and extend base adapter in that.
Base Adapter can be extended to create a custom Adapter for displaying a
custom list item.
Important Note: ArrayAdapter is also an implementation of BaseAdapter.
Let’s discuss all these functions in detail:
1. getCount():
The getCount() function returns the total number of items to be displayed in a list. It
counts the value from array list size() method or an array’s length. For example, if we
have an list of elements in an arraylist and we have to display the items in a list view
then we can count the total number of elements using the size function and then
that integer value is returned by the function getCount() as shown below.
@Override
public int getCount() {
int count=arrayList.size(); //counts the total number of elements from the
arrayList
return count;//returns the total count to adapter
}
2. getView(int i, View view, ViewGroup viewGroup):
This function is automatically called when the list item view is ready to be displayed
or about to be displayed. In this function we set the layout for list items using
LayoutInflater class and then add the data to the views like ImageView, TextView etc.
Below is the getView function’s example code with explanation included in which we
set the layout using LayoutInflater and then get the view’s id and implement them.
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
28. view = inflter.inflate(R.layout.activity_gridview, null);//set layout for
displaying items
ImageView icon = (ImageView) view.findViewById(R.id.icon);//get id for image view
icon.setImageResource(flags[i]);//set image of the item’s
return view;
}
3. getItem(int i):
This function is used to Get the data item associated with the specified position in
the data set to obtain the corresponding data of the specific location in the
collection of data items.
Below is the example code in which we returns the array list‘s item according to
position.
@Override
public Object getItem(int i) {
return arrayList.get(i);
}
4. getItemId(int i):
As for the getItemId (int position), it returns the corresponding to the position item
ID. The function returns a long value of item position to the adapter.
Below is the code in which we returns the position.
@Override
public long getItemId(int i) {
return i;
}
2.Views
GridView
In android GridView is a view group that display items in two dimensional scrolling grid
(rows and columns), the grid items are not necessarily predetermined but they are
automatically inserted to the layout using a ListAdapter. Users can then select any grid item
by clicking on it. GridView is default scrollable so we don’t need to use ScrollView or
anything else with GridView.
GridView is widely used in android applications. An example of GridView is your
default Gallery, where you have number of images displayed using grid.
29. Adapter Is Used To Fill Data In Gridview: To fill the data in a GridView we simply use
adapter and grid items are automatically inserted to a GridView using an Adapter which
pulls the content from a source such as an arraylist, array or database. You can read
full Adapter tutorial here.
GridView in Android Studio: Gridview is present inside Containers. From there you can drag
and drop on virtual mobile screen to create it. Alternatively you can also XML code to create
it.
Important Note: numColumns property has to be specified otherwise GridView behaves like
a ListView with just singleChoice. In the above image numColumns property specified that
there is 3 columns to show, if we set it to auto_fit then it automatically display as many
column as possible to fill the available space of the screen. Even if the phone is in portrait
mode or landscape mode it automatically fill the whole space.
Example
ImageAdapter.java
package com.example.androidhive;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.pic_1, R.drawable.pic_2,
R.drawable.pic_3, R.drawable.pic_4,
R.drawable.pic_5, R.drawable.pic_6,
R.drawable.pic_7, R.drawable.pic_8,
R.drawable.pic_9, R.drawable.pic_10,
R.drawable.pic_11, R.drawable.pic_12,
R.drawable.pic_13, R.drawable.pic_14,
R.drawable.pic_15
};
// Constructor
30. public ImageAdapter(Context c){
mContext = c;
}
@Override
public int getCount() {
return mThumbIds.length;
}
@Override
public Object getItem(int position) {
return mThumbIds[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
31. ScrollView
In android ScrollView can hold only one direct child. This means that, if you have
complex layout with more views(Buttons, TextViews or any other view) then you
must enclose them inside another standard layout like Table Layout, Relative
Layout or Linear Layout. You can specify layout_width and layout_height to adjust
width and height of screen. You can specify height and width in dp(density pixel) or
px(pixel). Then after enclosing them in a standard layout, enclose the whole layout in
ScrollView to make all the element or views scrollable.
WebView
In Android, WebView is a view used to display the web pages in application.
This class is the basis upon which you can roll your own web browser or simply
use it to display some online content within your Activity. We can also specify
HTML string and can show it inside our application using a WebView. Basically,
WebView turns application into a web application.
Internet Permission Required For Webview:
Important Note: In order for Activity to access the Internet and load the web pages
in a WebView, we must add the internet permissions to our Android Manifest file
(Manifest.xml).
Below code define the internet permission in our manifest file to access the internet
in our application.
<!--Add this before application tag in AndroidManifest.xml-->
<uses-permission android:name="android.permission.INTERNET" />
Methods of WebView In Android:
loadUrl() – Load a web page in our WebView
loadUrl(String url)
This function is used to load a web page in a web view of our application. In
this method we specify the url of the web page that should be loaded in a web view.
loadData() – Load Static Html Data on WebView
loadData(String data, String mimeType, String encoding)
This method is used to load the static HTML string in a web view. loadData() function
takes html string data, mime-type and encoding param as three parameters.
canGoBack() – Move to one page back if a back history exist
32. This method is used to specify whether the web view has a back history item or not.
This method returns a Boolean value either true or false. If it returns true then
goBack() method is used to move one page back.
canGoForward() – Move one page forward if forward history exist
This method is used to specify whether the web view has a forword history item or
not. This method returns a Boolean value either true or false. If it returns true then
goForword() method is used to move one page forword.
clearHistory() – clear the WebView history
This method is used to clear the web view forward and backward history.
SearchView
In Android, SearchView widget provide search user interface where users can enter a
search query and then submit a request to search provider. It shows a list of query
suggestions or results if available and allow the users to pick a suggestion or result to
launch into.
SearchView Methods In Android:
1.getQuery(): This function is used to get the query string currently in the text field of a
search view. This method returns CharSequence type value.
Below we get the query String from a search view.
SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); //
inititate a search view
CharSequence query = simpleSearchView.getQuery(); // get the query string
currently in the text field
2. getQueryHint(): This function is used for getting the hint text that will be displayed
in the query text field. This method returns a CharSequence type value.
Below is an example code which get the hint text that will be displayed in the query
text field of a search view.
SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); //
inititate a search view
CharSequence queryHint = simpleSearchView.getQueryHint(); // get the hint text
that will be displayed in the query text field
3. isIconfiedByDefault(): This method returns the default iconified state of the
search field. This method returns a Boolean value either true or false.
Below we get the default state of the search field.
33. SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); //
inititate a search view
boolean isIconfied=simpleSearchView.isIconfiedByDefault(); // checks default
iconified state of the search field
4. setIconifiedByDefault(Boolean iconify): This method is used to set the default or
resting state of the search field. In this method we set Boolean value true or false.
Important Note: When a SearchView is used in an Action Bar as an action view for
collapsible menu item then it needs to be set to iconified by default using
setIconfiedByDefault(true) function. If you want the search field to always be visible,
then call setIconifiedByDefault(false). true is the default value for this function. You
can also set iconfied from xml by using iconfiedByDefault property to true or false.
Below we set the iconified by default value to false .
SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); //
inititate a search view
simpleSearchView.setIconifiedByDefault(false); // set the default or resting
state of the search field
5. setQueryHint(CharSequence hint): This method is used to set the hint text to
display in the query text field. This method support CharSequence type value.
Below we set the query hint for a SearchView.
SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); //
inititate a search view
simpleSearchView.setQueryHint("Search View"); // set the hint text to display in
the query text field
6.setOnQueryTextFocusChangeListener(OnFocusChangeListenerlistener): This
listener inform when the focus of the query text field changes.
In the below code we show the use of setOnQueryTextFocusChangeListener() of
SearchView.
SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); //
inititate a search view
// perform set on query text focus change listener event
simpleSearchView.setOnQueryTextFocusChangeListener(new
View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// do something when the focus of the query text field changes
34. }
});
7. setOnQueryTextListener(OnQueryTextListenerlistener): It is a user action within
the SearchView.
TabHost
In Android, TabHost is a Container for tabbed window view. This object holds two
children one is set of tab labels that the user clicks to select a specific tab and other is
a FrameLayout object that displays the content of that page.
Whenever we need to enter or display a lot of information in one activity. A simple
and effective method is to use tabs in your interface form which is done using
TabHost in Android.
Important Note: A Tabhost holds two children’s from which one is use to set the
labels that the users clicks to select tab other is a FrameLayout that is used to display
the content of that page. It means when you select any label (or you can say change
the tab) the FrameLayout is used to display the content for that particular tab.
Important Note: For Using TabHost in our MainActivity we need to extend
TabActivity instead of Activity.
Methods Of TabHost:
1. addTab(TabSpec tabSpec): This method is used to add a tab onto a tab widget.
Whenever we specify a new tab using TabSpec class we need to add that tab in our
TabHost.
Below is an example code with explanation in which we specify a tab using TabSpec
class and then add that tab in our tab host using addTab method.
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost); // initiate
TabHost
TabHost.TabSpec tabSpec = tabHost.newTabSpec("tab1"); // Create a new TabSpec
using tab host
tabSpec.setIndicator(view); // set the “Tab 1” as an indicator
Intent intent = new Intent(this, MyActivity.class);
tabSpec.setContent(intent); // specify an intent to use to launch an activity as
the tab content
tabHost.addTab(tabSpec); // add a tab in Tab widget
2. clearAllTabs(): This method is used to remove all the tabs from the tab widget
associated with TabHost.
Below is an example code in which Firstly we add two tabs and then remove all the
tabs from a tab widget.
35. TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost); // initiate
TabHost
TabHost.TabSpec tabSpec = tabHost.newTabSpec("tab1"); // Create a new TabSpec
using tab host
tabSpec.setIndicator("Tab 1"); // set the “Tab 1” as an indicator
Intent intent = new Intent(this, MyActivity.class);
tabSpec.setContent(intent);
TabHost.TabSpec tabSpec1 = tabHost.newTabSpec("tab2"); // Create a new TabSpec
using tab host
tabSpec1.setIndicator("Tab 2"); // set the “Tab 2” as an indicator
Intent intent1 = new Intent(this, MyActivity.class);
tabSpec1.setContent(intent1); // specify an intent to use to launch an activity as
the tab content
tabHost.addTab(tabSpec); // add first tab in Tab widget
tabHost.addTab(tabSpec1); // add second tab in Tab widget
tabHost.clearAllTabs(); // clear all the tabs from tab widget
3. setCurrentTab(int index): This method is used to set the current selected tab from
the tab widget. By default a tab host set first tab as current tab but we can change it
by using this function.
Below is an example code in which firstly we add two tabs and then set the second
tab as current tab.
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost); // initiate
TabHost
TabHost.TabSpec tabSpec = tabHost.newTabSpec("tab1"); // Create a new TabSpec
using tab host
tabSpec.setIndicator("Tab 1"); // set the “Tab 1” as an indicator
Intent intent = new Intent(this, MyActivity.class);
tabSpec.setContent(intent);
TabHost.TabSpec tabSpec1 = tabHost.newTabSpec("tab2"); // Create a new TabSpec
using tab host
tabSpec1.setIndicator("Tab 2"); // set the “Tab 2” as an indicator
Intent intent1 = new Intent(this, MyActivity.class);
tabSpec1.setContent(intent1); // specify an intent to use to launch an activity as
the tab content
tabHost.addTab(tabSpec); // add first tab in Tab widget
tabHost.addTab(tabSpec1); // add second tab in Tab widget
tabHost.setCurrentTab(1); // set second tab as current selected tab
36. 4. setOnTabChangedListener(OnTabChangeListenerl): This method is used to
register a callback to be invoked when the selected state of any of the items in this
list changes.
Below we show how to use setOnTabChangedListener in TabHost.
// perform set on tab changed listener on tab host
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
// Add code Here
}
});
Expandable Listview
In Android, ExpandableListView is a View that shows items in a vertically scrolling
two level list. Different from the listview by allowing two level groups which can
individually be expanded to show its children. Each group can be expanded or
collapsed individually to show or hide its children items.
We can attach listeners events to the Expandable ListView to listen for OnClick or any
other events on the Group or the individual children. Adapters are used to supply or
control the data that will be displayed in a Expandable ListView.
Important Note: You cannot use the value wrap_content for the height attribute of a
ExpandableListView in XML if the parent’s size is not strictly specified. In other words
we mean if the parent were ScrollView then you could not specify wrap_content
since it can be of any length. However, you can use wrap content if the
ExpandableListView parent has a specific size, such as 200 pixels.
Adapter Used In ExpandableListView In Android:
An adapter is a bridge between UI component and data source that helps us to fill
data in UI component. It holds the data and send the data to Adapter view then view
can takes the data from the adapter view and shows the data on different views like
as ExpandableListView or other Views. The implementation of this interface will
provide access to the data of the children (categorized by groups), and also
instantiate views for the children and groups.
In Android for supplying data in a ExpandableListView following adapters are used.
1. ExpandableListAdapter
2. BaseExpandableListAdapter
3. SimpleExpandableListAdapter
37. Multimedia API
1.Audio
Android provides many ways to control playback of audio/video files and
streams. One of this way is through a class called MediaPlayer.
Android is providing MediaPlayer class to access built-in mediaplayer
services like playing audio,video e.t.c. In order to use MediaPlayer, we
have to call a static Method create() of this class. This method returns
an instance of MediaPlayer class. Its syntax is as follows −
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
The second parameter is the name of the song that you want to play.
You have to make a new folder under your project with name raw and
place the music file into it.
Once you have created the Mediaplayer object you can call some
methods to start or stop the music. These methods are listed below.
mediaPlayer.start();
mediaPlayer.pause();
On call to start() method, the music will start playing from the
beginning. If this method is called again after the pause() method, the
music would start playing from where it is left and not from the
beginning.
In order to start music from the beginning, you have to
call reset() method. Its syntax is given below.
mediaPlayer.reset();
Sr.No Method & description
1
isPlaying()
This method just returns true/false indicating the song is playing or not
2 seekTo(position)
This method takes an integer, and move song to that particular second
38. 3
getCurrentDuration()
This method returns the current position of song in milliseconds
4
getDuration()
This method returns the total time duration of song in milliseconds
5 reset()
This method resets the media player
6 release()
This method releases any resource attached with MediaPlayer object
7 setVolume(float leftVolume, float rightVolume)
This method sets the up down volume for this player
8 setDataSource(FileDescriptor fd)
This method sets the data source of audio/video file
9
selectTrack(int index)
This method takes an integer, and select the track from the list on that
particular index
10 getTrackInfo()
This method returns an array of track information
Example
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
41. 2.VideoView
In Android, VideoView is used to display a video file. It can load images from various
sources (such as content providers or resources) taking care of computing its
measurement from the video so that it can be used for any layout manager,
providing display options such as scaling and tinting.
Important Note: VideoView does not retain its full state when going into the
background. In particular it does not restore the current play position and play state.
Applications should save and restore these
in onSaveInstanceState(Bundle) and onRestoreInstanceState(Bundle).
Methods Used in VideoView:
1. setVideoUri(Uri uri): This method is used to set the absolute path of the video
file which is going to be played. This method takes a Uri object as an
argument.
2. setMediaController(MediaController controller): This method of VideoView is used
to set the controller for the controls of video playback.
3. start(): This method of VideoView is used to start the playback of video file.
4. pause(): This method of video view is used to pause the current playback.
Chapter-2
1.Data Storage & SQLite
1.Shared Preference
Android provides many ways of storing data of an application. One of this
way is called Shared Preferences. Shared Preferences allow you to save
and retrieve data in the form of key,value pair.
In order to use shared preferences, you have to call a method
getSharedPreferences() that returns a SharedPreference instance
pointing to the file that contains the values of preferences.
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
The first parameter is the key and the second parameter is the MODE.
Sr.No Mode & description
42. 1
MODE_APPEND
This will append the new preferences with the already existing preferences
2
MODE_ENABLE_WRITE_AHEAD_LOGGING
Database open flag. When it is set , it would enable write ahead logging by default
3
MODE_MULTI_PROCESS
This method will check for modification of preferences even if the sharedpreference instance
has already been loaded
4
MODE_PRIVATE
By setting this mode, the file can only be accessed using calling application
5
MODE_WORLD_READABLE
This mode allow other application to read the preferences
6
MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences
You can save something in the sharedpreferences by using SharedPreferences.Editor class.
You will call the edit method of SharedPreference instance and will receive it in an editor
object. Its syntax is −
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
2.Android file System
Android File System Structure/Architecture/Layout Details
Most of the Android user are using their Android phone just for calls, SMS, browsing and
basic apps, But form the development prospective, we should know about Android internal
structure. Android uses several partitions (like boot, system, recovery,data etc) to organize
files and folders on the device just like Windows OS. Each of these partitions has it’s own
functionality, But most of us don’t know the significance of each partition and its contents.
43. In this article, we will take you on a tour of Android partitions. So lets start the android file
system tutorial.
There are mainly 6 partitions in Android phones, tablets and other Android devices. Below is
the list of partition for Android File System. Note that there might be some other partitions
available, it differs from Model to Model. But logically below 6 partitions can be found in
any Android devices.
/boot
/system
/recovery
/data
/cache
/misc
Also Below are the for SD Card Fie System Partitions.
/sdcard
/sd-ext
Please Note: Only /sdcard partition can be found in all Android devices and the rest are
present only in select devices.
Know Your Android Device Partition Size using adb Command
You can know which partitions are available along with the partition size for all partition in
your android device. Go through the below image and run the adb command as shown in that
image. For more adb commands, you can read my atricle Useful adb Commands for
Android Development. Also for more details for android architecture, you can read my
article Android Architecture.
44. Note: boot and recovery partition is not displayed in the above image. So after adb shell, you
need to run mount command. like cat proc/mounts
/boot
This is the boot partition of your Android device, as the name suggests. It includes the
android kernel and the ramdisk. The device will not boot without this partition. Wiping this
partition from recovery should only be done if absolutely required and once done, the device
must NOT be rebooted before installing a new one, which can be done by installing a ROM
that includes a /boot partition.
/system
As the name suggests, this partition contains the entire Android OS, other than the kernel and
the ramdisk. This includes the Android GUI and all the system applications that come pre-
installed on the device. Wiping this partition will remove Android from the device without
rendering it unbootable, and you will still be able to put the phone into recovery or bootloader
mode to install a new ROM.
/recovery
This is specially designed for backup. The recovery partition can be considered as an
alternative boot partition, that lets the device boot into a recovery console for performing
advanced recovery and maintenance operations on it.
/data
Again as the name suggest, it is called userdata partition. This partition contains the user’s
data like your contacts, sms, settings and all android applications that you have installed.
While you perform factory reset on your device, this partition will be wiped out, Then your
device will be in the state, when you used for the first time or the way it was after the last
official or custom ROM installation.
45. /cache
I hope you have some idea about cache, as you are expert on internet browsing. This is the
partition where Android stores frequently accessed data and app components. Wiping the
cache doesn’t effect your personal data but simply gets rid of the existing data there, which
gets automatically rebuilt as you continue using the device.
/misc
This partition contains miscellaneous system settings in form of on/off switches. These
settings may include CID (Carrier or Region ID), USB configuration and certain hardware
settings etc. This is an important partition and if it is corrupt or missing, several of the
device’s features will will not function normally.
/sdcard
This is not a partition on the internal memory of the device but rather the SD card. In terms of
usage, this is your storage space to use as you see fit, to store your media, documents, ROMs
etc. on it. Wiping it is perfectly safe as long as you backup all the data you require from it, to
your computer first. Though several user-installed apps save their data and settings on the SD
card and wiping this partition will make you lose all that data.
On devices with both an internal and an external SD card – devices like the Samsung Galaxy
S and several tablets – the /sdcard partition is always used to refer to the internal SD card. For
the external SD card – if present – an alternative partition is used, which differs from device
to device. In case of Samsung Galaxy S series devices, it is /sdcard/sd while in many other
devices, it is /sdcard2. Unlike /sdcard, no system or app data whatsoever is stored
automatically on this external SD card and everything present on it has been added there by
the user. You can safely wipe it after backing up any data from it that you need to save.
/sd-ext
This is not a standard Android partition, but has become popular in the custom ROM scene. It
is basically an additional partition on your SD card that acts as the /data partition when used
with certain ROMs that have special features called APP2SD+ or data2ext enabled. It is
especially useful on devices with little internal memory allotted to the /data partition. Thus,
users who want to install more programs than the internal memory allows can make this
partition and use it with a custom ROM that supports this feature, to get additional storage for
installing their apps. Wiping this partition is essentially the same as wiping the /data partition
– you lose your contacts, SMS, market apps and settings.
Now when you install a new binary, you can know what you’re going to loose, make sure to
backup your data before flash new binary in your android device.
I hope this small tutorial will help you at it’s best. If you have nay query or comments, please
share with us, we will get back to you asap.
46. 3.Internal storage
Android provides many kinds of storage for applications to store their
data. These storage places are shared preferences, internal and external
storage, SQLite storage, and storage via network connection.
Here we are going to look at the internal storage. Internal storage is the
storage of the private data on the device memory.
By default these files are private and are accessed by only your
application and get deleted , when user delete your application.
Writing file
In order to use internal storage to write some data in the file, call the
openFileOutput() method with the name of the file and the mode. The
mode could be private , public etc. Its syntax is given below −
FileOutputStream fOut = openFileOutput("file name here",MODE_WORLD_READABLE);
The method openFileOutput() returns an instance of FileOutputStream.
So you receive it in the object of FileInputStream. After that you can call
write method to write data on the file. Its syntax is given below −
String str ="data";
fOut.write(str.getBytes());
fOut.close();
Reading file
In order to read from the file you just created , call the openFileInput()
method with the name of the file. It returns an instance of
FileInputStream. Its syntax is given below −
FileInputStream fin = openFileInput(file);
After that, you can call read method to read one character at a time from
the file and then you can print it. Its syntax is given below −
int c;
String temp="";
while((c = fin.read())!=-1){
temp = temp +Character.toString((char)c);
}
47. //string temp contains all the data of the file.
fin.close();
Android provides many kinds of storage for applications to store their
data. These storage places are shared preferences, internal and external
storage, SQLite storage, and storage via network connection.
In this chapter we are going to look at the internal storage. Internal
storage is the storage of the private data on the device memory.
By default these files are private and are accessed by only your
application and get deleted , when user delete your application.
Writing file
In order to use internal storage to write some data in the file, call the
openFileOutput() method with the name of the file and the mode. The
mode could be private , public e.t.c. Its syntax is given below −
FileOutputStream fOut = openFileOutput("file name here",MODE_WORLD_READABLE);
The method openFileOutput() returns an instance of FileOutputStream.
So you receive it in the object of FileInputStream. After that you can call
write method to write data on the file. Its syntax is given below −
String str ="data";
fOut.write(str.getBytes());
fOut.close();
Reading file
In order to read from the file you just created , call the openFileInput()
method with the name of the file. It returns an instance of
FileInputStream. Its syntax is given below −
FileInputStream fin = openFileInput(file);
After that, you can call read method to read one character at a time from
the file and then you can print it. Its syntax is given below −
int c;
String temp="";
48. while((c = fin.read())!=-1){
temp = temp +Character.toString((char)c);
}
//string temp contains all the data of the file.
fin.close();
Apart from the the methods of write and close, there are other methods
provided by the FileOutputStream class for better writing files. These
methods are listed below −
Sr.No Method & description
1
FileOutputStream(File file, boolean append)
This method constructs a new FileOutputStream that writes to file.
2
getChannel()
This method returns a write-only FileChannel that shares its position with
this stream
3
getFD()
This method returns the underlying file descriptor
4
write(byte[] buffer, int byteOffset, int byteCount)
This method Writes count bytes from the byte array buffer starting at
position offset to this stream
Apart from the the methods of read and close, there are other methods provided by
the FileInputStream class for better reading files. These methods are listed below −
Sr.No Method & description
1
available()
This method returns an estimated number of bytes that can be read or skipped without blocking
49. for more input
2
getChannel()
This method returns a read-only FileChannel that shares its position with this stream
3
getFD()
This method returns the underlying file descriptor
4
read(byte[] buffer, int byteOffset, int byteCount)
This method reads at most length bytes from this stream and stores them in the byte array b
starting at offset
Content Provider, Intent & Notifications
1. Accessing built in 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. 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.
CONTENTPROVIDER
sometimes it is required to share data across applications. This is where content providers become
very useful.
Content providers let you centralize content in one place and have many different applications
access it as needed. A content provider behaves very much like a database where you can query it,
edit its content, as well as add or delete content using insert(), update(), delete(), and query()
methods. In most cases this data is stored in an SQlite database.
A content provider is implemented as a subclass of ContentProvider class and must implement a
standard set of APIs that enable other applications to perform transactions.
50. publicclassMyApplicationextendsContentProvider{}
Content URIs
To query a content provider, you specify the query string in the form of a URI which has following
format −
<prefix>://<authority>/<data_type>/<id>
Here is the detail of various parts of the URI –
Sr.No Part & Description
1
prefix
This is always set to content://
2
authority
This specifies the name of the content provider, for example contacts, browser etc. For
third-party content providers, this could be the fully qualified name, such
as com.tutorialspoint.statusprovider
3
data_type
This indicates the type of data that this particular provider provides. For example, if you
are getting all the contacts from the Contacts content provider, then the data path would
be people and URI would look like thiscontent://contacts/people
4
id
This specifies the specific record requested. For example, if you are looking for contact
number 5 in the Contacts content provider then URI would look like
this content://contacts/people/5.
Create Content Provider
This involves number of simple steps to create your own content provider.
First of all you need to create a Content Provider class that extends
the ContentProviderbaseclass.
51. Second, you need to define your content provider URI address which will be used to access the
content.
Next you will need to create your own database to keep the content. Usually, Android uses
SQLite database and framework needs to override onCreate() method which will use SQLite
Open Helper method to create or open the provider's database. When your application is
launched, the onCreate() handler of each of its Content Providers is called on the main
application thread.
Next you will have to implement Content Provider queries to perform different database specific
operations.
Finally register your Content Provider in your activity file using <provider> tag.
Here is the list of methods which you need to override in Content Provider class to have
your Content Provider working −
CONTENTPROVIDER
onCreate() This method is called when the provider is started.
query() This method receives a request from a client. The result is returned as a Cursor object.
insert()This method inserts a new record into the content provider.
delete() This method deletes an existing record from the content provider.
update() This method updates an existing record from the content provider.
getType() This method returns the MIME type of the data at the given URI.
WHAT IS PARSING?JSON PARSING & XML PARSING?
Breaking a data block into smaller chunks by following a set of rules, so that it can be more easily
interpreted, managed, or transmitted by a computer. Spreadsheet programs, for example, parse a
52. data to fit it into a cell of certain size
JSON
JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the
best alternative for XML. This chapter explains how to parse the JSON file and extract necessary
information from it.
Android provides four different classes to manipulate JSON data. These classes are
JSONArray,JSONObject,JSONStringer and JSONTokenizer.
JSON - Elements
An JSON file consist of many components. Here is the table defining the components of an JSON file
and their description −
Sr.No Component & description
1 Array([)
In a JSON file , square bracket ([) represents a JSON array
2 Objects({)
In a JSON file, curly bracket ({) represents a JSON object
3 Key
A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
4 Value
Each key has a value that could be string , integer or double e.t.c
JSON - Parsing
For parsing a JSON object, we will create an object of class JSONObject and specify a string
containing JSON data to it. Its syntax is −
String in;
JSONObject reader = new JSONObject(in);
The last step is to parse the JSON. A JSON file consist of different object with different key/value pair
e.t.c. So JSONObject has a separate function for parsing each of the component of JSON file. Its
syntax is given below −
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
53. temperature = main.getString("temp");
The method getJSONObject returns the JSON object. The method getString returns the string value
of the specified key.
Apart from the these methods , there are other methods provided by this class for better parsing
JSON files. These methods are listed below −
Sr.No Method & description
1 get(String name)
This method just Returns the value but in the form of Object type
2 getBoolean(String name)
This method returns the boolean value specified by the key
3 getDouble(String name)
This method returns the double value specified by the key
4 getInt(String name)
This method returns the integer value specified by the key
5 getLong(String name)
This method returns the long value specified by the key
6 length()
This method returns the number of name/value mappings in this object..
7 names()
This method returns an array containing the string names in this object.
Example:-
public class MainActivity2 extends ActionBarActivity {
HttpResponse response;
JSONArray user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
54. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final HttpClient client = new DefaultHttpClient();
final HttpPost request = new HttpPost("http://10.9.65.8/ankit/display.php");
try {
response = client.execute(request);
String result = inputStreamToString(response.getEntity().getContent());
JSONObject myjson = new JSONObject(result);
user=myjson.getJSONArray("user");
for (int i=0;i<user.length();i++)
{
JSONObject c =user.getJSONObject(i);
String data= c.getString("id") + "-" + c.getString("name")+"-" + c.getString("salary")+"-" +
c.getString("desc"));
Toast.makeText(getApplcationContect,""+data,Toast.LANGTH_LONG).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(MainActivity2.this,e+"",Toast.LENGTH_LONG).show();
}
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
55. // Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
//Log.e(TAG, e.getLocalizedMessage(), e);
e.printStackTrace();
}
// Return full string
return total.toString();
}
}
XML
XML stands for Extensible Mark-up Language.XML is a very popular format and commonly used for
sharing data on the internet. This chapter explains how to parse the XML file and extract necessary
information from it.
Android provides three types of XML parsers which are DOM,SAX and XMLPullParser. Among all of
them android recommend XMLPullParser because it is efficient and easy to use. So we are going to
use XMLPullParser for parsing XML.
XML - Elements
An xml file consist of many components. Here is the table defining the components of an XML file
and their description.
Sr.No Component & description
1 Prolog
An XML file starts with a prolog. The first line that contains the information about a file is
prolog
2 Events
An XML file has many events. Event could be like this. Document starts , Document ends, Tag
start , Tag end and Text e.t.c
3 Text
Apart from tags and events, and xml file also contains simple text. Such as GB is a text in the
country tag.
4 Attributes
Attributes are the additional properties of a tag such as value etc
56. XMLPullParser
Android recommends to use XMLPullParser to parse the xml file than SAX and DOM because it is
fast.
The org.xmlpull.v1.XmlPullParser interface provides the functionality to parse the XML document
using XMLPullParser.
Events of XmlPullParser
The next() method of XMLPullParser moves the cursor pointer to the next event. Generally, we use
four constants (works as the event) defined in the XMLPullParser interface.
START_TAG :An XML start tag was read.
TEXT :Text content was read; the text content can be retrieved using the getText() method.
END_TAG : An end tag was read.
END_DOCUMENT :No more events are available
SAX Parser
Android provides the facility to parse the xml file using SAX, DOM etc. parsers. The SAX parser
cannot be used to create the XML file, It can be used to parse the xml file only.
Advantage of SAX Parser over DOM
It consumes less memory than DOM.
DOM Parser
We can parse the xml document by dom parser also. It can be used to create and parse the xml file.
Advantage of DOM Parser over SAX
It can be used to create and parse the xml file both but SAX parser can only be used to parse the xml
file.
Disadvantage of DOM Parser over SAX
It consumes more memory than SAX.
Example
file.xml
<?xml version="1.0"?>
<records>
<employee>