Android Development
Android Development
DEVELOPMENT
Using android studio and windows
Belal Noory
Software Developer
Table of Contents
Overview .................................................................................................................................................... 5
What is android? ..................................................................................................................................... 5
Feature of android .................................................................................................................................. 5
Android Applications............................................................................................................................... 6
.................................................................................................................................................................... 7
Environmental Setup .................................................................................................................................. 7
Step 1 – download and setup Java development Kit (JDK)...................................................................... 7
Step 2 – Download and install Android studio ........................................................................................ 9
Step 3 – Download and install Genymotion .......................................................................................... 10
Architecture .............................................................................................................................................. 11
Linux Kernel .......................................................................................................................................... 12
Libraries ................................................................................................................................................ 12
Android Runtime................................................................................................................................... 12
Application Framework ......................................................................................................................... 12
Applications .......................................................................................................................................... 12
Application Components .......................................................................................................................... 13
Activities ............................................................................................................................................... 13
Services ................................................................................................................................................. 13
Broadcast Receivers .............................................................................................................................. 14
Content Provider ................................................................................................................................... 14
Additional Components ........................................................................................................................ 14
Hello World Example ................................................................................................................................ 15
Creating Android Application ................................................................................................................ 15
Anatomy of Android Application........................................................................................................... 16
The Main Activity File ............................................................................................................................ 17
The Manifest File .................................................................................................................................. 17
The Strings File ...................................................................................................................................... 18
The R File .............................................................................................................................................. 19
The Layout File ...................................................................................................................................... 19
Running the Application........................................................................................................................ 19
Resources Organizing & Accessing ............................................................................................................ 20
Organize Resources............................................................................................................................... 20
Alternative Resources ........................................................................................................................... 21
Accessing Resources ............................................................................................................................. 21
ACCESSING RESOURCES IN CODE .......................................................................................................... 21
ACCESSING RESOURCES IN XML ............................................................................................................ 22
.................................................................................................................................................................. 23
Activities ................................................................................................................................................... 23
Services ..................................................................................................................................................... 25
Broadcast Receivers .................................................................................................................................. 29
Creating the Broadcast Receiver ........................................................................................................... 29
Registering Broadcast Receiver ................................................................................................................. 29
Broadcasting Custom Intents ................................................................................................................ 30
Content Providers ..................................................................................................................................... 32
Content URIs ......................................................................................................................................... 32
Create Content Provider ....................................................................................................................... 33
Fragments ................................................................................................................................................. 39
Fragment Life Cycle ............................................................................................................................... 40
How to use Fragments? ........................................................................................................................ 40
Intents and Filters ..................................................................................................................................... 44
Intent Objects ....................................................................................................................................... 44
ACTION ................................................................................................................................................. 45
DATA ..................................................................................................................................................... 46
CATEGORY............................................................................................................................................. 46
Android Intent Standard Categories ..................................................................................................... 46
EXTRAS .................................................................................................................................................. 47
Android Intent standard Extra Data ...................................................................................................... 47
FLAGS .................................................................................................................................................... 47
COMPONENT NAME ............................................................................................................................. 47
Types of Intents .................................................................................................................................... 47
EXPLICIT INTENTS .................................................................................................................................. 48
IMPLICIT INTENTS ................................................................................................................................. 48
Intent Filters.......................................................................................................................................... 51
UI Layouts ................................................................................................................................................. 55
Android Layout Types ........................................................................................................................... 56
Linear Layout ............................................................................................................................................ 56
LinearLayout Attributes .................................................................................................................... 56
Relative Layout ..................................................................................................................................... 57
Table Layout Android ............................................................................................................................ 59
TableLayout Attributes ..................................................................................................................... 59
Absolute Layout .................................................................................................................................... 60
Frame Layout ........................................................................................................................................ 60
List View ................................................................................................................................................ 61
ListView Attributes ............................................................................................................................ 61
Array Adapter ....................................................................................................................................... 62
Simple Cursor Adapter .......................................................................................................................... 62
GridView ............................................................................................................................................... 63
GridView Attributes .......................................................................................................................... 63
UI Controls ................................................................................................................................................ 68
Android UI Controls .............................................................................................................................. 68
TextView ........................................................................................................................................... 69
EditText ............................................................................................................................................. 70
AutoCompleteTextView .................................................................................................................... 71
Button ............................................................................................................................................... 72
ImageButton ..................................................................................................................................... 72
CheckBox .......................................................................................................................................... 72
ToggleButton .................................................................................................................................... 73
RadioButton ...................................................................................................................................... 73
RadioGroup ....................................................................................................................................... 73
Event Handling .......................................................................................................................................... 74
Event Listeners & Event Handlers ......................................................................................................... 74
Event Listeners Registration: ................................................................................................................ 75
Using an Anonymous Inner Class ...................................................................................................... 75
Activity class implements the Listener interface. .............................................................................. 75
Using Layout file activity_main.xml to specify event handler directly. ............................................. 76
Notifications ............................................................................................................................................. 77
Create and Send Notifications .............................................................................................................. 77
STEP 1 - CREATE NOTIFICATION BUILDER ......................................................................................... 77
STEP 2 - SETTING NOTIFICATION PROPERTIES .................................................................................. 77
STEP 3 - ATTACH ACTIONS ................................................................................................................ 78
STEP 4 - ISSUE THE NOTIFICATION .................................................................................................... 78
The [Link] Class .................................................................................................. 78
Android Alert Dialogs ................................................................................................................................ 80
Android SQLite Database .......................................................................................................................... 82
Database – Package .............................................................................................................................. 82
Database – Creation.............................................................................................................................. 82
Database – Insertion ............................................................................................................................. 83
Database – Fetching.............................................................................................................................. 83
Database - Helper class ......................................................................................................................... 84
Android PHP/MySQL ................................................................................................................................. 86
PHP – PDO (MYSQL) .............................................................................................................................. 86
CREATING DATABASE ........................................................................................................................ 86
CREATING TABLES ............................................................................................................................. 87
FUNCTIONS FOR INSERTING AND SELECTING VALUES FROM TABLES............................................... 88
ANDROID - CONNECTING MYSQL.......................................................................................................... 89
CONNECTING VIA POST METHOD ......................................................... Error! Bookmark not defined.
CONNECTING VIA GET METHOD ........................................................... Error! Bookmark not defined.
CHAPTER
1
Overview
What is android?
A ndroid is an open source and Linux-based Operating System for mobile devices such as
smartphones and tablet computers.
Android was developed by the Open Handset Alliance, led by Google, and other companies.
Android offers a unified approach to application development for mobile devices which means
developers need only develop for Android, and their applications should be able to run on different
devices powered by Android.
The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007
where as the first commercial version, Android 1.0, was released in September 2008.
On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly
Bean.
Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms
of functionality and performance.
The source code for Android is available under free and open source software licenses.
Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel
changes, under the GNU General Public License version 2.
Feature of android
Android is a powerful operating system competing with Apple 4GS and supports great features. Few of
them are listed below:
Feature Description
Beautiful UI Android OS basic screen provides a beautiful and intuitive user interface
Connectivity GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX
Storage SQLite, a lightweight relational database, is used for data storage purposes.
Media support H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI,
WAV, JPEG, PNG, GIF, and BMP
Messaging SMS and MMS
Web browser Based on the open-source Web Kit layout engine, coupled with Chrome's V8
JavaScript engine supporting HTML5 and CSS3.
Multi-touch Android has native support for multi-touch which was initially made available in
handsets such as the HTC Hero.
Multi-tasking User can jump from one task to another and same time various application can
run simultaneously.
Resizable widgets s Widgets are resizable, so users can expand them to show more content or
shrink them to save space
Multi-Language Supports single direction and bi-directional text.
GCM Google Cloud Messaging (GCM) is a service that lets developers send short
message data to their users on Android devices, without needing a proprietary
sync solution.
Wi-Fi Direct A technology that lets apps discover and pair directly, over a high-bandwidth
peer-to-peer connection.
Android Beam A popular NFC-based technology that lets users instantly share, just by touching
two NFC enabled phones together.
Android Applications
Android applications are usually developed in the Java language using the Android Software
Development Kit. Once developed, Android applications can be packaged easily and sold out either
through a store such as Google Play or the Amazon Appstore.
Android powers hundreds of millions of mobile devices in more than 190 countries around the world.
It's the largest installed base of any mobile platform and growing fast. Every day more than 1 million
new Android devices are activated worldwide. This tutorial has been written with an aim to teach you
how to develop and package Android application. We will start from environment setup for Android
application programming and then drill down to look into various aspects of Android applications
CHAPTER
Environmental Setup
Y ou will be glad to know that you can start your Android application development on either of the
following operating systems but we will just cover windows:
Second point is that all the required tools to develop Android applications are freely available and can
be downloaded from the Web.
Following is the list of software's you will need before you start your Android application programming.
Java JDK (latest version)
Android Studio (latest version)
Genymotion
5. Click on Edit and then past the address of directory where java is installed and then press ok.
Step 2 – Download and install Android studio
You can download the latest version of Android SDK from Android official website: Android Studio
Download.
So just download and run this exe which will launch Android studio Setup wizard to guide you through
out of the installation, so just follow the instructions carefully.
Finally you will have Android studio installed on your machine.
Launch android studio after installation and you will have to download about 500MB files which are
required to run android studio. After downloading run the android studio and create your first android
application and then android studio will start downloading 200MB file which is required to run android
application and that’s all.
Congratulations you have successfully installed android studio.
After downloading Genymotion create a Genymotion account so you can access virtual devices
and then open the Genymotion, login into your account and you will have list of devices you can
add simple.
Note: now we have both android studio and Genymotion so we have to install Genymotion
plugin in android studio so we can easily access the virtual device inside android studio, please
follow the steps:
Open android studio => Files => Setting => Plugins => Genymotion
1
CHAPTER
3
Architecture
A ndroid 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
This provides basic system functionality like process management, memory management, device
management 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 application
data, libraries to play and record audio and video, SSL libraries responsible for Internet security etc.
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
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
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, and Games etc.
CHAPTER
4
Application Components
A pplication components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file [Link] that describes
each component of the application and how they interact. There are following four main components
that can be used within an Android application:
Feature Description
Activities They dictate the UI and handle the user interaction to the smartphone screen
Services They handle background processing associated with an application.
Broadcast Receivers They handle communication between Android OS and applications.
Content Providers They handle data and database management issues.
Activities
An activity represents a single screen with a user interface.
For example, an email application might have one activity that shows a list of new emails, another
activity to compose an email, and another activity for reading emails.
If an application has more than one activity, then one of them should be marked as the activity that is
presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows:
Services
A service is a component that runs in the background to perform long-running operations.
For example, a service might play music in the background while the user is in a different application, or
it might fetch data over the network without blocking user interaction with an activity.
A service is implemented as a subclass of Service class as follows:
// this is my service
}
Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from the system.
For example, applications can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and is available for them to use, so this is broadcast receiver who will
intercept this communication and will initiate appropriate action.
A broadcast receiver is implemented as a subclass of Broadcast Receiver class and each message is
broadcasted as an Intent object.
Public class MyReceiver extends BroadcastReceiver {
// this is my receiver
Content Provider
A content provider component supplies data from one application to others on request.
Such requests are handled by the methods of the ContentResolver class.
The data may be stored in the file system, the database or somewhere else entirely.
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.
Public class MyContentProvider extends ContentProvider {
We will go through these tags in detail while covering application components in individual chapters.
Additional Components
There are additional components which will be used in the construction of above mentioned entities,
their logic, and wiring between them. These components are:
Component Description
Fragments Represents a behavior or a portion of user interface in an Activity.
Views UI elements that are drawn onscreen including buttons, lists forms etc.
Layouts View hierarchies that control screen format and appearance of the views.
Intents Messages wiring components together.
Resources External elements, such as strings, constants and drawables pictures.
Manifest Configuration file for the application.
CHAPTER
5
Hello World Example
L et us start actual programming with Android studio. Before you start writing your first example
using Android studio, you have to make sure that you have setup your Android development
environment properly as explained in previews chapter.
So let us proceed to write a simple Android Application which will print "Hello World!”.
Select Basic Activity and press Next then Name your application as HelloWorld and select Java as
language, finally press finish.
Anatomy of Android Application
Before you run your app, you should be aware of a few directories and files in the Android project:
Manifests / [Link]
This is the manifest file which describes the fundamental characteristics of the app and defines each
of its components.
Java
This contains the .java source files for your project. By default, it includes a [Link]
file having an activity class that runs when your app is launched using the app icon.
res/drawable
This is a directory for drawable objects like images.
res/layout
This is a directory for files that define your app's user interface.
res/values
This is a directory for other various XML files that contain a collection of resources, such as strings and
colors definitions.
Following section will give a brief overview few of the important application files.
The Main Activity File
The main activity code is a Java file [Link]. This is the actual application file which ultimately
gets converted to a Dalvik executable and runs your application. Following is the default code generated
by the application wizard for Hello World! Application:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
Here, [Link].activity_main refers to the activity_main.xml file located in the res/layout folder.
The onCreate() method is one of many methods that are fired when an activity is loaded.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/[Link]">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/[Link]">
<intent-filter>
<action android:name="[Link]" />
</manifest>
The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified
class name of the Activity subclass and the android:label attributes specifies a string to use as the label
for the activity. You can specify multiple activities using <activity> tags.
The action for the intent filter is named [Link] to indicate that this activity serves
as the entry point for the application.
The category for the intent-filter is [Link] to indicate that the
application can be launched from the device's launcher icon.
The @string refers to the [Link] file explained below. Hence, @string/app_name refers to the
app_name string defined in the [Link] file, which is "HelloWorld".
Similar way, other strings get populated in the application.
Following is the list of tags which you will use in your manifest file to specify different Android
application components:
<activity> elements for activities
<service> elements for services
<receiver> elements for broadcast receivers
<provider> elements for content providers
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Hello World" />
</RelativeLayout>
This is an example of simple RelativeLayout which we will study in a separate chapter. The TextView is
an Android control used to build the GUI and it have various attribuites like
android:layout_width,android:layout_height which are being used to set its width and height etc.
1 2
Congratulations!!! You have developed your first Android Application and now just keep following rest
of the tutorial step by step to become a great Android Developer. All the best.
CHAPTER
6
Resources Organizing & Accessing
T here are many more items which you use to build a good Android application. Apart from coding
for the application, you take care of various other resources like static content that your code uses, such
as bitmaps, colors, layout definitions, user interface strings, animation instructions, and more. These
resources are always maintained separately in various sub-directories under res/ directory of the
project. This tutorial will explain you how you can organize your application resources, specify
alternative resources and access them in your applications.
Organize Resources
You should place each type of resource in a specific subdirectory of your project's res/ directory.
The res/ directory contains all the resources in various subdirectories. Here we have an image resource,
two layout resources, and a string resource file. Following table gives a detail about the resource
directories supported inside project res/ directory.
Directory Resource Type
anim/ XML files that define property animations. They are saved in res/anim/ folder
and accessed from the [Link] class.
color/ XML files that define a state list of colors. They are saved in res/color/ and
accessed from the [Link] class.
drawable/ Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps, state
lists, shapes, animation drawables. They are saved in res/drawable/ and
accessed from the [Link] class.
layout/ XML files that define a user interface layout. They are saved in res/layout/ and
accessed from the [Link] class.
menu/ XML files that define application menus, such as an Options Menu, Context
Menu, or Sub Menu. They are saved in res/menu/ and accessed from
[Link] class.
raw/ Arbitrary files to save in their raw form. You need to
[Link]() with the resource ID, which is
[Link] to open such raw files.
values/ XML files that contain simple values, such as strings, integers, and colors. For
example, here are some filename conventions for resources you can create in
this directory: [Link] for resource arrays, and accessed from the [Link]
class. [Link] for resource integers, and accessed from the
[Link]. [Link] for resource boolean, and accessed from the [Link]
class. [Link] for color values, and accessed from the [Link] class.
[Link] for dimension values, and accessed from the [Link] class.
[Link] for string values, and accessed from the [Link] class. [Link]
for styles, and accessed from the [Link] class.
xml/ Arbitrary XML files that can be read at runtime by calling [Link]().
You can save various configuration files here which will be used at run time.
Alternative Resources
Your application should provide alternative resources to support specific device configurations. For
example, you should include alternative drawable resources ( [Link] ) for different screen resolution
and alternative string resources for different languages. At runtime, Android detects the current device
configuration and loads the appropriate resources for your application.
To specify configuration-specific alternatives for a set of resources, follow the following steps:
Create a new directory in res/ resources _named in the form -. Here resources_name will be any of the
resources mentioned in the above table, like layout, drawable etc. The qualifier will specify an individual
configuration for which these resources are to be used.
Accessing Resources
During your application development you will need to access defined resources either in your code, or in
your layout XML files. Following section explains how to access your resources in both the scenarios:
Here first line of the code make use of [Link] to get ImageView defined with id
myimageview in a Layout file.
Second line of code makes use of [Link] to get an image with name myimage available in
drawable sub-directory under /res.
Example 2:
Consider next example where res/values/[Link] has following definition:
<? xml version="1.0" encoding="utf-8" ?>
<resources>
<string name="hello">>Hello, World!</string>
</resources>
Now you can set the text on a TextView object with ID msg using a resource ID as follows:
TextView msgTextView = (TextView) findViewById([Link]);
[Link]([Link]);
Example 3:
Consider a layout res/layout/activity_main.xml with the following definition:
<? xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="[Link]
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
This application code will load this layout for an Activity, in the onCreate() method as follows:
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].main_activity);
}
Now you can use these resources in the following layout file to set the text color and text string as
follows:
<? xml version="1.0" encoding="utf-8" ?>
<EditText xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="@color/opaque_red"
android:text="@string/hello" />
CHAPTER
7
Activities
A n activity represents a single screen with a user interface. For example, an email application might
have one activity that shows a list of new emails, another activity to compose an email, and another
activity for reading emails. If an application has more than one activity, then one of them should be
marked as the activity that is presented when the application is launched.
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
anActivity 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 as shown in the
below Activity lifecycle diagram:
Callback Description
onCreate() This is the first callback and called when the activity is first created.
onStart() This callback is called when the activity becomes visible to the user.
onResume() This is called when the user starts interacting with the application.
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.
onStop() This callback is called when the activity is no longer visible.
onDestroy() This callback is called before the activity is destroyed by the system.
onRestart() This callback is called when the activity restarts after stopping it.
Example:
This example will take you through simple steps to show Android application activity life cycle.
1 => Create New Project using android studio and name your project.
2 => Modify the main activity file ([Link]) as explained below.
3 => Run the application in the virtual device.
}
CHAPTER
8
Services
A service is a component that runs in the background to perform long-running operations without
needing to interact with the user. For example, a service might play music in the background while the
user is in a different application, or it might fetch data over the network without blocking user
interaction with an activity. A service can essentially take two states:
State Description
Started A service is started when an application component, such as an activity, starts
it by calling startService(). Once started, a service can run in the background
indefinitely, even if the component that started it is destroyed.
Bound A service is bound when an application component binds to it by
callingbindService(). A bound service offers a client-server interface that
allows components to interact with the service, send requests, get results, and
even do so across processes with interprocess communication (IPC).
Following will the modified content of [Link] file. Here we have added tag to include our
service:
<manifest xmlns:android="[Link]
package="[Link]"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]"/>
</intent-filter>
</activity>
<service android:name=".MyService" />
</application>
</manifest>
CHAPTER
9
Broadcast Receivers
B roadcast Receivers simply respond to broadcast messages from other applications or from the
system itself. These messages are sometime called events or intents. For example, applications can also
initiate broadcasts to let other applications know that some data has been downloaded to the device
and is available for them to use, so this is broadcast receiver who will intercept this communication and
will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system broadcasted
intents:
Creating the Broadcast Receiver.
Registering Broadcast Receiver.
There is one additional steps in case you are going to implement your custom intents then you will have
to create and broadcast those intents.
Creating the Broadcast Receiver
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the
onReceive() method where each message is received as a Intent object parameter.
Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver
MyReceiverand implemented logic inside onReceive() will be executed.
Modify [Link] file as below. Here we have added tag to include our service:
<manifest xmlns:android="[Link]
package="[Link]"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]"/>
</intent-filter>
</activity>
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="[Link].CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
Let's try to run our modified Hello World! Application we just modified, I assume you had created your
AVD while doing environment setup. To run the app from android studio click run icon and you
application will be opened in your running virtual device.
CHAPTER
10
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. Each
Android applications runs in its own process with its own permissions which keeps an application data
hidden from another application. But 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 a 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.
Public class MyContentProvider extends ContentProvider { }
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>
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 [Link]
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 this
content://contacts/people
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
thiscontent://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.
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:
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.
Example:
This example will explain you how to create your own ContentProvider. So let's follow the following
steps to similar to what we followed while creating Hello World Example:
1 => Create a new java file called [Link].
2 => Register your content provider in your [Link] file using <provider .../> tag.
3 => Modify the default content of res/layout/activity_main.xml file to include a small GUI to add
Student’s records.
4 => Define required constants in res/values/[Link] file.
5 => Modify main activity file [Link] to add two new methods onClickAddName() and
onClickRetrieveStudents ().
Following is the content of the modified main activity [Link], We have added two new
methods onClickAddName () and onClickRetrieveStudents () to handle user interaction with the
application.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate([Link], menu);
return true;
}
public void onClickAddName(View view) {
// Add a new student record
ContentValues values = new ContentValues();
[Link]([Link],
((EditText)findViewById([Link])).getText().toString());
[Link]([Link],
((EditText)findViewById([Link])).getText().toString());
Uri uri = getContentResolver().insert(
StudentsProvider.CONTENT_URI, values);
[Link](getBaseContext(),
[Link](), Toast.LENGTH_LONG).show();
}
public void onClickRetrieveStudents(View view) {
// Retrieve student records
String URL = "content://[Link]/students";
Uri students = [Link](URL);
Cursor c = managedQuery(students, null, null, null, "name");
if ([Link]()) {
do{
[Link](this,
[Link]([Link](StudentsProvider._ID)) +
", " + [Link]([Link]( [Link])) +
", " + [Link]([Link]( [Link])),
Toast.LENGTH_SHORT).show();
} while ([Link]());
}
}
}
Create new file [Link] and following is its contents:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class StudentsProvider extends ContentProvider {
static final String PROVIDER_NAME = "[Link]";
static final String URL = "content://" + PROVIDER_NAME + "/students";
static final Uri CONTENT_URI = [Link](URL);
static final String _ID = "_id";
static final String NAME = "name";
static final String GRADE = "grade";
private static HashMap<String, String> STUDENTS_PROJECTION_MAP;
static final int STUDENTS = 1;
static final int STUDENT_ID = 2;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
[Link](PROVIDER_NAME, "students", STUDENTS);
[Link](PROVIDER_NAME, "students/#", STUDENT_ID);
}
/**
* Database specific constant declarations
*/
private SQLiteDatabase db;
static final String DATABASE_NAME = "College";
static final String STUDENTS_TABLE_NAME = "students";
static final int DATABASE_VERSION = 1;
static final String CREATE_DB_TABLE =
" CREATE TABLE " + STUDENTS_TABLE_NAME +
" (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
" name TEXT NOT NULL, " +
" grade TEXT NOT NULL);";
/**
* Helper class that actually creates and manages
* the provider's underlying data repository.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) { [Link](CREATE_DB_TABLE); }
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
[Link]("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME); onCreate(db); }
}
@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
/**
* Create a write able database which will trigger its
* creation if it doesn't already exist.
*/
db = [Link]();
return (db == null)? false:true;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
/**
* Add a new student record
*/
long rowID = [Link]( STUDENTS_TABLE_NAME, "", values);
/**
* If record is added successfully
*/
if (rowID > 0)
{
Uri _uri = [Link](CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Failed to add a record into " + uri);
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
switch ([Link](uri)) {
case STUDENTS:
[Link](STUDENTS_PROJECTION_MAP);
break;
case STUDENT_ID:
[Link]( _ID + "=" + [Link]().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == ""){
/**
* By default sort on student names
*/
sortOrder = NAME;
}
Cursor c = [Link](db, projection, selection, selectionArgs,
null, null, sortOrder);
/**
* register to watch a content URI for changes
*/
[Link](getContext().getContentResolver(), uri);
return c;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch ([Link](uri)){
case STUDENTS:
count = [Link](STUDENTS_TABLE_NAME, selection, selectionArgs);
break;
case STUDENT_ID:
String id = [Link]().get(1);
count = [Link]( STUDENTS_TABLE_NAME, _ID + " = " + id +
( ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch ([Link](uri)){
case STUDENTS:
count = [Link](STUDENTS_TABLE_NAME, values,
selection, selectionArgs);
break;
case STUDENT_ID:
count = [Link](STUDENTS_TABLE_NAME, values, _ID +
" = " + [Link]().get(1) +
( ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri );
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public String getType(Uri uri) {
switch ([Link](uri)){
/**
* Get all student records
*/
case STUDENTS:
return "[Link]/[Link]";
/**
* Get a particular student
*/
case STUDENT_ID:
return "[Link]/[Link]";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
}
Following will the modified content of [Link] file. Here we have added tag to include our
content provider:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
package="[Link]"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="[Link]"
android:label="@string/app_name" >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
<provider android:name="StudentsProvider"
android:authorities="[Link]">
</provider>
</application>
</manifest>
Let's try to run our modified Hello World! Application we just modified, I assume you had created your
AVD while doing environment setup. To run the app from android studio click run icon and you
application will be opened in your running virtual device.
CHAPTER
11
Fragments
A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity
which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-
activity. Following are important points about fragment:
A fragment has its own layout and its own behavior with its own lifecycle callbacks.
You can add or remove fragments in an activity while the activity is running.
You can combine multiple fragments in a single activity to build a multi-pane UI.
A fragment can be used in multiple activities.
Fragment life cycle is closely related to the lifecycle of its host activity which means when the activity is
paused, all the fragments available in the activity will also be stopped.
A fragment can implement a behavior that has no user interface component.
Fragments were added to the Android API in Honeycomb version of Android which API version 11.
You create fragments by extending Fragment class and you can insert a fragment into your activity
layout by declaring the fragment in the activity's layout file, as an element.
Prior to fragment introduction, we had a limitation because we can show only a single activity on the
screen at one given point in time. So we were not able to divide device screen and control different
parts separately.
But with the introduction of fragment we got more flexibility and removed the limitation of having a
single activity on the screen at a
time. Now we can have a single
activity but each activity can
comprise of multiple fragments
which will have their own
layout, events and complete
lifecycle.
Following is a typical example
of how two UI modules defined
by fragments can be combined
into one activity for a tablet
design, but separated for a
handset design.
Fragment Life Cycle
Android fragments have their own life cycle very similar to
an android activity. This section briefs different stages of
its life cycle.
}
Create two fragment files LM_Fragement.java and PM_Fragment.java.
Following is the content of LM_Fragement.java file:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class LM_Fragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
return [Link](
[Link].lm_fragment, container, false);
}
}
Following is the content of PM_Fragement.java file:
public class PM_Fragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
return [Link](
[Link].pm_fragment, container, false);
}
}
Create two layout files lm_fragement.xml and pm_fragment.xml under res/layout directory.
Following is the content of lm_fragement.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#7bae16">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/landscape_message"
android:textColor="#000000"
android:textSize="20px" />
<!-- More GUI components go here -->
</LinearLayout>
Following is the content of pm_fragment.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#7bae16">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/portrait_message"
android:textColor="#000000"
android:textSize="20px" />
<!-- More GUI components go here -->
</LinearLayout>
<fragment
android:name="[Link]"
android:id="@+id/pm_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
Let's try to run our modified Hello World! Application we just modified, I assume you had created your
AVD while doing environment setup. To run the app from android studio click run icon and you
application will be opened in your running virtual device.
CHAPTER
12
Intents and Filters
A n Android Intent is an object carrying an intent ie. Message from one component to another
component with-in the application or outside the application. The intents can communicate messages
among any of the three core components of an application - activities, services, and broadcast receivers.
The intent itself, an Intent object, is a passive data structure holding an abstract description of an
operation to be performed.
For example, let's assume that you have an Activity that needs to launch an email client and sends an
email using your Android device. For this purpose, your Activity would send an ACTION_SEND along with
appropriate chooser, to the Android Intent Resolver. The specified chooser gives the proper interface for
the user to pick how to send your email data.
For example, assume that you have an Activity that needs to open URL in a web browser on your
Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the Android
Intent Resolver to open given URL in the web browser. The Intent Resolver parses through a list of
Activities and chooses the one that would best match your Intent, in this case, the Web Browser
Activity. The Intent Resolver then passes your web page to the web browser and starts the Web Browser
Activity.
There are separate mechanisms for delivering intents to each type of component - activities, services,
and broadcast receivers.
Method Description
[Link]() The Intent object is passed to this method to launch a new activity or get
an existing activity to do something new.
[Link]() The Intent object is passed to this method to initiate a service or deliver
new instructions to an ongoing service.
[Link]() The Intent object is passed to this method to deliver the message to all
interested broadcast receivers.
Intent Objects
An Intent object is a bundle of information which is used by the component that receives the intent plus
information used by the Android system. An Intent object can contain the following components based
on what it is communicating or going to perform:
ACTION
This is mandatory part of the Intent object and is a string naming the action to be performed — or, in
the case of broadcast intents, the action that took place and is being reported. The action largely
determines how the rest of the intent object is structured. The Intent class defines a number of action
constants corresponding to different intents.
Activity Action Intent & Description
ACTION_ALL_APPS
List all the applications available on the device.
ACTION_ANSWER
Handle an incoming phone call.
ACTION_ATTACH_DATA
Used to indicate that some piece of data should be attached to some other place
ACTION_BATTERY_LOW
This broadcast corresponds to the "Low battery warning" system dialog.
ACTION_BOOT_COMPLETED
This is broadcast once, after the system has finished booting.
ACTION_CALL
Perform a call to someone specified by the data.
ACTION_CALL_BUTTON
The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call.
ACTION_CAMERA_BUTTON
The "Camera Button" was pressed.
ACTION_CHOOSER
Display an activity chooser, allowing the user to pick what they want to before proceeding.
ACTION_CONFIGURATION_CHANGED
The current device Configuration (orientation, locale, etc) has changed.
ACTION_DATE_CHANGED
The date has changed.
ACTION_DEVICE_STORAGE_LOW
A sticky broadcast that indicates low memory condition on the device.
ACTION_DIAL Dial
A number as specified by the data.
ACTION_HEADSET_PLUG
Wired Headset plugged in or unplugged.
ACTION_POWER_CONNECTED
External power has been connected to the device.
ACTION_SCREEN_OFF
Sent after the screen turns off.
ACTION_SCREEN_ON
Sent after the screen turns on.
ACTION_SENDTO
Send a message to someone specified by the data.
ACTION_VOICE_COMMAND
Start Voice Command.
ACTION_WEB_SEARCH
Perform a web search.
DATA
The URI of the data to be acted on and the MIME type of that data. For example, if the action field is
ACTION_EDIT, the data field would contain the URI of the document to be displayed for editing.
The setData() method specifies data only as a URI, setType() specifies it only as a MIME type, and
setDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData() and the type
by getType().
Some examples of action/data pairs are:
Action/Data Pair & Description
ACTION_VIEW content://contacts/people/1
Display information about the person whose identifier is "1".
ACTION_DIAL content://contacts/people/1
Display the phone dialer with the person filled in.
ACTION_VIEW [Link]
Display the phone dialer with the given number filled in.
ACTION_DIAL [Link]
Display the phone dialer with the given number filled in
ACTION_EDIT content://contacts/people/1
Edit information about the person whose identifier is "1"
ACTION_VIEW content://contacts/people/
Display a list of people, which the user can browse through.
CATEGORY
The category is an optional part of Intent object and it's a string containing additional information about
the kind of component that should handle the intent. The addCategory() method places a category in an
Intent object, removeCategory() deletes a category previously added, and getCategories() gets the set
of all categories currently in the object.
Android Intent Standard Categories
Following table lists down various important Android Intent Standard Categories. You can check Android
Official Documentation for a complete list of Categories:
Categories & Description
CATEGORY_APP_BROWSER
Used with ACTION_MAIN to launch the browser application.
CATEGORY_APP_CALCULATOR
Display the phone dialer with the person filled in.
CATEGORY_APP_CALENDAR
Used with ACTION_MAIN to launch the calendar application.
CATEGORY_APP_CONTACTS
Used with ACTION_MAIN to launch the contacts application.
CATEGORY_APP_EMAIL
Used with ACTION_MAIN to launch the email application.
CATEGORY_APP_GALLERY
Used with ACTION_MAIN to launch the gallery application.
EXTRAS
This will be in key-value pairs for additional information that should be delivered to the component
handling the intent. The extras can be set and read using the putExtras() and getExtras() methods
respectively.
Android Intent standard Extra Data
Extra Data & Description
EXTRA_ALARM_COUNT
Used as an int extra field in AlarmManager intents to tell the application being invoked how many
pending alarms are being delivered with the intent.
EXTRA_ALLOW_MULTIPLE
Used to indicate that a ACTION_GET_CONTENT intent can allow the user to select and return
multiple items.
EXTRA_BCC A String[]
Holding e-mail addresses that should be blind carbon copied.
EXTRA_EMAIL A String[]
Holding e-mail addresses that should be delivered to.
EXTRA_LOCAL_ONLY
Used to indicate that a ACTION_GET_CONTENT intent should only return data that is on the local
device.
EXTRA_TEXT
A constant Char Sequence that is associated with the Intent, used with ACTION_SEND to supply the
literal data to be sent.
FLAGS
These flags are optional part of Intent object and instruct the Android system how to launch an activity,
and how to treat it after it’s launched.
COMPONENT NAME
This optional field is an android Component Name object representing either Activity, Service or
BroadcastReceiver class. If it is set, the Intent object is delivered to an instance of the designated class
otherwise Android uses other information in the Intent object to locate a suitable target. The
component name is set by setComponent(), setClass(), or setClassName() and read by getComponent().
Types of Intents
There are following two types of intents supported by Android till version 4.1.
1. EXPLICIT INTENTS
2. IMPLICIT INTENTS
EXPLICIT INTENTS
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(this, [Link]);
[Link]("Key1", "ABC");
[Link]("Key2", "123");
// Starts TargetActivity
startActivity(i);
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
Bundle extras = getIntent().getExtras();
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:
// Implicit Intent by specifying a URI
Intent i = new Intent(Intent.ACTION_VIEW, [Link]("[Link]
Example:
Following example shows the functionality of a Android Intent to launch various Android built-in
applications.
1 => Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout.
2 => Modify [Link] file and add the code to define two listeners corresponding two
buttons ie. Start Browser and Start Phone.
3 => Modify res/values/[Link] to define required constant values.
4 => Run the application to launch Android emulator and verify the result of the changes done in the
application.
Following is the content of the modified main activity [Link].
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
Button startBrowser = (Button) findViewById([Link].start_browser);
[Link](new [Link]() {
public void onClick(View view) {
Intent i = new Intent([Link].ACTION_VIEW,
[Link]("[Link]
startActivity(i);
}
});
Button startPhone = (Button) findViewById([Link].start_phone);
[Link](new [Link]() {
public void onClick(View view) {
Intent i = new Intent([Link].ACTION_VIEW,
[Link]("[Link]
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action
// bar if it is present.
getMenuInflater().inflate([Link], menu);
return true;
}
}
Following will be the content of res/layout/activity_main.xml file:
<LinearLayout xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/start_browser"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/start_browser"/>
<Button android:id="@+id/start_phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/start_phone" />
</LinearLayout>
Let's try to run our modified Hello World! Application we just modified, I assume you had created your
AVD while doing environment setup. To run the app from android studio click run icon and you
application will be opened in your running virtual device.
Similar way you can launch phone interface using Start Phone button, which will allow you to dial
already given phone number.
Intent Filters
You have seen how an Intent has been used to call another activity. Android OS uses filters to pinpoint
the set of Activities, Services, and Broadcast receivers that can handle the Intent with help of specified
set of action, categories, data scheme associated with an Intent. You will use element in the manifest
file to list down actions, categories and data types associated with any activity, service, or broadcast
receiver. Following is an example of a part of [Link] file to specify a CustomActivity which
can be invoked by either of the two mentioned actions, one category, and one data:
<activity android:name=".CustomActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="[Link]" />
<action android:name="[Link]" />
<category android:name="[Link]" />
<data android:scheme="http" />
</intent-filter>
</activity>
Once this activity is defined along with above mentioned filters, other activities will be able to invoke
this activity using either the [Link], or using the [Link] action provided
their category is [Link].
The <data> element specifies the data type expected by the activity to be called and for above example
our custom activity expects the data to start with the [Link]
There may be a situation that an intent can pass through the filters of more than one activity or service,
the user may be asked which component to activate. An exception is raised if no target can be found.
Example:
Following example is a modification of the above example. Here we will see how Android resolves
conflict if one intent is invoking two activities defined in, next how to invoke a custom activity using a
filter and third one is an exception case if Android does not file appropriate activity defined for an
intent.
1 => Add a new [Link] file to have one custom activity which will be invoked by different
intents.
2 => Add one layout XML file res/layout/custom_view.xml and add a simple <TextView> to show the
passed data through intent.
3 => Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout.
4 => Modify [Link] file and add the code to define three listeners corresponding to three
buttons defined in layout file.
5 => Modify [Link] to add <intent filter> to define rules for your intent to invoke
custom activity.
Following is the content of the modified main activity [Link].
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// First intent to use ACTION_VIEW action with correct data
Button startBrowser_a = (Button) findViewById([Link].start_browser_a);
startBrowser_a.setOnClickListener(new [Link]() {
public void onClick(View view) {
Intent i = new Intent([Link].ACTION_VIEW,
[Link]("[Link]
startActivity(i);
}
});
// Second intent to use LAUNCH action with correct data
Button startBrowser_b = (Button) findViewById([Link].start_browser_b);
startBrowser_b.setOnClickListener(new [Link]() {
public void onClick(View view) {
Intent i = new Intent("[Link]",
[Link]("[Link]
startActivity(i);
}
});
// Third intent to use LAUNCH action with incorrect data
Button startBrowser_c = (Button) findViewById([Link].start_browser_c);
startBrowser_c.setOnClickListener(new [Link]() {
public void onClick(View view) {
Intent i = new Intent("[Link]",
[Link]("[Link]
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the
// action bar if it is present.
getMenuInflater().inflate([Link], menu);
return true;
}
}
Following is the content of the [Link]:
public class CustomActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].custom_view);
TextView label = (TextView) findViewById([Link].show_data);
Uri url = getIntent().getData();
[Link]([Link]());
}
}
<Button android:id="@+id/start_browser_b"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/start_browser_b"/>
<Button android:id="@+id/start_browser_c"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/start_browser_c"/>
</LinearLayout>
<TextView android:id="@+id/show_data"
android:layout_width="fill_parent"
android:layout_height="400dp"/>
</LinearLayout>
Following is the default content of [Link]:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
package="[Link]"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="[Link]"
android:label="@string/app_name" >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
<activity android:name="[Link]"
android:label="@string/app_name">
<intent-filter>
<action android:name="[Link]" />
<action android:name="[Link]" />
<category android:name="[Link]" />
<data android:scheme="http" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run our modified Hello World! Application we just modified, I assume you had created your
AVD while doing environment setup. To run the app from android studio click run icon and you
application will be opened in your running virtual device.
CHAPTER
13
UI Layouts
T he 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.
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 usingView/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.
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout may contain
any type of widgets such as buttons, labels, textboxes, and so on.
Following is a simple example of XML file having LinearLayout:
Once your layout is defined, you can load the layout resource from your application code, in
[Link]() callback implementation as shown below:
setContentView([Link].activity_main);
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.
Layout & Description
Linear Layout
Linear Layout is a view group that aligns all children in a single direction, vertically or horizontally.
Relative Layout
RelativeLayout is a view group that displays child views in relative positions.
Table Layout
Table Layout is a view that groups views into rows and columns.
Absolute Layout
Absolute Layout enables you to specify the exact location of its children.
Frame Layout
The Frame Layout is a placeholder on screen that you can use to display a single view.
List View
List View is a view group that displays a list of scrollable items.
Grid View
Grid View is a View Group that displays items in a two-dimensional, scrollable grid.
Linear Layout
Android LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally.
LinearLayout Attributes
Following are the important attributes specific to LinearLayout:
Attribute Description
android:id This is the ID which uniquely identifies the layout.
This must be a boolean value, either "true" or "false" and prevents the
android:baselineAligned
layout from aligning its children's baselines.
This is drawable to use as a vertical divider between buttons. You use a
android:divider
color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
This specifies how an object should position its content, on both the X and
android:gravity Y axes. Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc
This specifies the direction of arrangmet and you will use "horizontal" for a
android:orientation
row, "vertical" for a column. The default is horizontal.
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link] <LinearLayout xmlns:android="[Link]
[Link]/apk/res/android" [Link]/apk/res/android"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:orientation=" horizontal " > android:orientation="vertical" >
<Button android:id="@+id/btnStartService" <Button android:id="@+id/btnStartService"
android:layout_width="150px" android:layout_width="150px"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="@string/start_service" android:text="@string/start_service"
Pause
Stop
Relative Layout
Android RelativeLayout enables you to specify how child views are positioned relative to each other. The
position of each view can be specified as relative to sibling elements or relative to the parent.
RelativeLayout Attributes
Following are the important attributes specific to RelativeLayout:
Attribute Description
android:id This is the ID which uniquely identifies the layout.
android:gravity This specifies how an object should position its content, on both the X and
Y axes. Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc.
android:ignoreGravity This indicates what view should not be affected by gravity.
Using RelativeLayout, you can align two elements by right border, or make one below another, centered
in the screen, centered left, and so on. By default, all child views are drawn at the top-left of the layout,
so you must define the position of each view using the various layout properties available
[Link] and few of the important attributes are given below:
Attribute Description
android:layout_above Positions the bottom edge of this view above the given anchor
view ID and must be a reference to another resource, in the
form "@[+][package:]type:name"
android:layout_alignBottom Makes the bottom edge of this view match the bottom edge of
the given anchor view ID and must be a reference to another
resource, in the form "@[+][package:]type:name".
android:layout_alignLeft Makes the left edge of this view match the left edge of the
given anchor view ID and must be a reference to another
resource, in the form "@[+][package:]type:name".
android:layout_alignParentBottom If true, makes the bottom edge of this view match the bottom
edge of the parent. Must be a boolean value, either "true" or
"false".
android:layout_alignParentEnd If true, makes the end edge of this view match the end edge of
the parent. Must be a boolean value, either "true" or "false".
android:layout_alignParentLeft If true, makes the left edge of this view match the left edge of
the parent. Must be a boolean value, either "true" or "false".
android:layout_alignParentRight If true, makes the right edge of this view match the right edge
of the parent. Must be a boolean value, either "true" or "false".
android:layout_alignParentStart If true, makes the start edge of this view match the start edge
of the parent. Must be a boolean value, either "true" or "false".
android:layout_alignParentTop If true, makes the top edge of this view match the top edge of
the parent. Must be a boolean value, either "true" or "false".
android:layout_alignRight Makes the right edge of this view match the right edge of the
given anchor view ID and must be a reference to another
resource, in the form "@[+][package:]type:name".
android:layout_alignStart Makes the start edge of this view match the start edge of the
given anchor view ID and must be a reference to another
resource, in the form "@[+][package:]type:name".
android:layout_alignTop Makes the top edge of this view match the top edge of the
given anchor view ID and must be a reference to another
resource, in the form "@[+][package:]type:name".
android:layout_below Positions the top edge of this view below the given anchor view
ID and must be a reference to another resource, in the form
"@[+][package:]type:name".
android:layout_centerHorizontal If true, centers this child horizontally within its parent. Must be
a boolean value, either "true" or "false".
android:layout_centerInParent If true, centers this child horizontally and vertically within its
parent. Must be a boolean value, either "true" or "false".
android:layout_centerVertical If true, centers this child vertically within its parent. Must be a
boolean value, either "true" or "false".
android:layout_toEndOf Positions the start edge of this view to the end of the given
anchor view ID and must be a reference to another resource, in
the form "@[+][package:]type:name".
android:layout_toLeftOf Positions the right edge of this view to the left of the given
anchor view ID and must be a reference to another resource, in
the form "@[+][package:]type:name".
android:layout_toRightOf Positions the left edge of this view to the right of the given
anchor view ID and must be a reference to another resource, in
the form "@[+][package:]type:name".
android:layout_toStartOf Positions the end edge of this view to the start of the given
anchor view ID and must be a reference to another resource, in
the form "@[+][package:]type:name".
android:collapseColumns This specifies the zero-based index of the columns to collapse. The
column indices must be separated by a comma: 1, 2, 5.
android:stretchColumns The zero-based index of the columns to stretch. The column indices must
be separated by a comma: 1, 2, 5.
<TableLayout xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow>
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</ TableLayout >
Absolute Layout
An Absolute Layout lets you specify exact locations (x/y coordinates) of its children. Absolute layouts are
less flexible and harder to maintain than other types of layouts without absolute positioning.
AbsoluteLayout Attributes
Following are the important attributes specific to AbsoluteLayout:
Attribute Description
android:id This is the ID which uniquely identifies the layout.
<AbsoluteLayout xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="OK"
android:layout_x="50px"
android:layout_y="361px" />
</AbsoluteLayout>
Frame Layout
Frame Layout is designed to block out an area on the screen to display a single item. Generally,
FrameLayout should be used to hold a single child view, because it can be difficult to organize child
views in a way that's scalable to different screen sizes without the children overlapping each other. You
can, however, add multiple children to a FrameLayout and control their position within the
FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.
FrameLayout Attributes
Following are the important attributes specific to FrameLayout:
Attribute Description
android:id This is the ID which uniquely identifies the layout.
android:foreground This defines the drawable to draw over the content and possible
values may be a color value, in the form of "#rgb", "#argb", "#rrggbb",
or "#aarrggbb".
android:foregroundGravity Defines the gravity to apply to the foreground drawable. The gravity
defaults to fill. Possible values are top, bottom, left, right, center,
center_vertical, center_horizontal etc.
android:measureAllChildren Determines whether to measure all children or just those in the
VISIBLE or INVISIBLE state when measuring. Defaults to false.
<FrameLayout xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="@drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_height="250px"
android:layout_width="250px"/>
<TextView
android:text="Frame Demo"
android:textSize="30px"
android:textStyle="bold"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
List View
Android ListView is a view which groups several items and display them in vertical scrollable list. The list
items are automatically inserted to the list using an Adapter that pulls content from a source such as an
array or database. An adapter actually bridges between UI components and the data source that fill data
into UI Component. Adapter can be used to supply the data to like spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding them
to an Adapter, which retrieves data from an external source and creates a View that represents each
data entry. Android provides several subclasses of Adapter that are useful for retrieving different kinds
of data and building views for an AdapterView ( ie. ListView or GridView). The two most common
adapters are ArrayAdapter and SimpleCursorAdapter. We will see separate examples for both the
adapters.
ListView Attributes
Following are the important attributes specific to GridView:
Attribute Description
android:id This is the ID which uniquely identifies the layout.
android:dividerHeight This specifies height of the divider. This could be in px, dp, sp, in, or mm.
android:entries Specifies the reference to an array resource that will populate the ListView.
android:footerDivider When set to false, the ListView will not draw the divider before each footer
sEnabled view. The default value is true.
android:headerDivide When set to false, the ListView will not draw the divider after each header
rsEnabled view. The default value is true.
Array Adapter
You can use this adapter when your data source is an array. By default, ArrayAdapter creates a view for
each array item by calling toString() on each item and placing the contents in a TextView. Consider you
have an array of strings you want to display in a ListView, initialize a new ArrayAdapter using a
constructor to specify the layout for each string and the string array:
ArrayAdapter adapter = new ArrayAdapter(this, [Link], StringArray);
Final argument is an array of strings which will be populated in the text view.
Once you have array adaptor created, then simply call setAdapter() on your ListView object as follows:
ListView listView = (ListView) findViewById([Link]);
[Link](adapter);
When you instantiate the SimpleCursorAdapter, pass the layout to use for each result, the Cursor
containing the results, and these two arrays:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, [Link].person_name_and_number,
cursor, fromColumns, toViews, 0);
ListView listView = getListView();
[Link](adapter);
GridView
Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the grid items
are not necessarily predetermined but they automatically inserted to the layout using a ListAdapter.
An adapter actually bridges between UI components and the data source that fill data into UI
Component. Adapter can be used to supply the data to like spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding them
to an Adapter, which retrieves data from an external source and creates a View that represents each
data entry.
GridView Attributes
Attribute Description
android:id This is the ID which uniquely identifies the layout.
android:columnWidth This specifies the fixed width for each column. This could be in px, dp,
sp, in, or mm.
android:gravity Specifies the gravity within each cell. Possible values are top, bottom,
left, right, center, center_vertical, center_horizontal etc.
android:horizontalSpacing Defines the default horizontal spacing between columns. This could be
in px, dp, sp, in, or mm.
android:numColumns Defines how many columns to show. May be an integer value, such as
"100" or auto_fit which means display as many columns as possible to
fill the available space.
android:stretchMode Defines how columns should stretch to fill the available empty space, if
any. This must be either of the values:
none: Stretching is disabled.
spacingWidth: The spacing between each column is stretched.
columnWidth: Each column is stretched equally.
spacingWidthUniform: The spacing between each column is uniformly
stretched.
android:verticalSpacing Defines the default vertical spacing between rows. This could be in px,
dp, sp, in, or mm.
Example:
This example will take you through simple steps to show how to create your own Android application
using GridView. We will be creating image gallery using GridView.
1 => Create A new android project and modify the default content of res/layout/activity_main.xml file
to include GridView content with the self-explanatory attributes.
2 => add few pictures in res/drawable folder.
3 => Create a new class called ImageAdapter that extends BaseAdapter. This class will implement
functionality of an adaptor to be used to fill the view.
4 => modify the [Link] file according to book file.
5 => run the application.
Following is the content of [Link].
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
[Link](new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), [Link]);
// Pass image index
[Link]("id", position);
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate([Link], menu);
return true;
}
}
CHAPTER
14
UI Controls
A n Android application user interface is everything that the user can see and interact with. You
have learnt about the various layouts that you can use to position your views in an activity.
This chapter will give you detail on various views.
A View is an object that draws something on the screen that the user can interact with and aViewGroup
is an object that holds other View (ViewGroup) objects in order to define the layout of the user
interface.
You define your layout in an XML file which offers a human-readable structure for the layout, similar to
HTML.
Android UI Controls
There are numbers of UI controls provided by Android that allow you to build the graphical user
interface for your app.
UI Control & Description
TextView
This control is used to display text to the user.
EditText
EditText is a predefined subclass of TextView that includes rich editing capabilities.
AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of
completion suggestions automatically while the user is typing.
Button
A push-button that can be pressed, or clicked, by the user to perform an action.
ImageButton
AbsoluteLayout enables you to specify the exact location of its children.
CheckBox
An on/off switch that can be toggled by the user.
ToggleButton
An on/off button with a light indicator.
RadioButton
The RadioButton has two states: either checked or unchecked.
RadioGroup
A RadioGroup is used to group together one or more RadioButtons.
ProgressBar
The ProgressBar view provides visual feedback about some ongoing tasks, such as when you are
performing a task in the background.
Spinner
A drop-down list that allows users to select one value from a set.
TimePicker
The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM
mode.
DatePicker
The DatePicker view enables users to select a date of the day.
TextView
A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text
editor, however the basic class is configured to not allow editing.
TextView Attributes
Following are the important attributes related to TextView control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change these
attributes are run time.
Attribute Description
android:id This is the ID which uniquely identifies the layout.
android:capitalize If set, specifies that this TextView has a textual input method and
should automatically capitalize what the user types.
Don't automatically capitalize anything - 0
Capitalize the first word of each sentence - 1
Capitalize the first letter of every word – 2
Capitalize every character - 3
android:cursorVisible Makes the cursor visible (the default) or invisible. Default is false.
android:editable If set to true, specifies that this TextView has an input method.
android:fontFamily Font family (named by string) for the text.
android:gravity Specifies how to align the text by the view's x- and/or y-axis when the
text is smaller than the view.
android:hint Hint text to display when the text is empty.
android:inputType The type of data being placed in a text field. Phone, Date, Time,
Number, Password etc.
android:maxHeight Makes the TextView be at most this many pixels tall.
android:textColor Text color. May be a color value, in the form of "#rgb", "#argb",
"#rrggbb", or "#aarrggbb".
android:textColorHint Color of the hint text. May be a color value, in the form of "#rgb",
"#argb", "#rrggbb", or "#aarrggbb".
android:textIsSelectable Indicates that the content of a non-editable text can be selected.
Possible value either "true" or "false".
android:textSize Size of the text. Recommended dimension type for text is "sp" for
scaled-pixels (example: 15sp).
android:textStyle Style (bold, italic, bolditalic) for the text. You can use or more of the
following values separated by '|'.
normal - 0
bold - 1
italic - 2
android:typeface Typeface (normal, sans, serif, monospace) for the text. You can use or
more of the following values separated by '|'.
normal - 0
sans – 1
serif - 2
monospace – 3
EditText
An EditText is an overlay over TextView that configures itself to be editable. It is the predefined subclass
of TextView that includes rich editing capabilities.
EditText Attributes
Following are the important attributes related to EditText control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change these
attributes are run time.
android:contentDescription This defines text that briefly describes content of the view.
android:onClick This is the name of the method in this View's context to invoke when
the view is clicked.
android:visibility This controls the initial visibility of the view.
AutoCompleteTextView
An AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion
suggestions automatically while the user is typing. The list of suggestions is displayed in drop down
menu. The user can choose an item from there to replace the content of edit box with.
AutoCompleteTextView Attributes
Following are the important attributes related to AutoCompleteTextView control.
Attribute Description
android:completionHint This defines the hint displayed in the drop down menu.
android:completionHintView This defines the hint view displayed in the drop down menu.
android:dropDownHorizontal The amount of pixels by which the drop down should be offset
Offset horizontally.
android:dropDownSelector This is the selector in a drop down list.
android:dropDownVerticalOff The amount of pixels by which the drop down should be offset
set vertically.
android:dropDownWidth This specifies the basic width of the dropdown.
android:onClick This is the name of the method in this View's context to invoke when
the view is clicked.
android:visibility This controls the initial visibility of the view.
ImageButton
An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its children. This
shows a button with an image (instead of text) that can be pressed or clicked by the user.
ImageButton Attributes
Attribute Description
android:adjustViewBounds Set this to true if you want the ImageView to adjust its bounds to
preserve the aspect ratio of its drawable.
android:baselineAlignBottom If true, the image view will be baseline aligned with based on its
bottom edge.
android:cropToPadding If true, the image will be cropped to fit within its padding.
CheckBox
A CheckBox is an on/off switch that can be toggled by the user. You should use check-boxes when
presenting users with a group of selectable options that are not mutually exclusive.
CheckBox Attributes
Following are the important attributes related to CheckBox control.
Attribute Description
android:text This is the Text to display.
android:baselineAlignBottom If true, the image view will be baseline aligned with based on its
bottom edge.
android:background This is a drawable to use as the background.
android:onClick This is the name of the method in this View's context to invoke when
the view is clicked.
android:visibility This controls the initial visibility of the view.
ToggleButton
A ToggleButton displays checked/unchecked states as a button. It is basically an on/off button with a
light indicator.
ToggleButton Attributes
Following are the important attributes related to ToggleButton control.
Attribute Description
android:disabledAlpha This is the alpha to apply to the indicator when disabled.
android:textOff This is the text for the button when it is not checked
android:onClick This is the name of the method in this View's context to invoke when
the view is clicked.
android:visibility This controls the initial visibility of the view.
RadioButton
A RadioButton has two states: either checked or unchecked. This allows the user to select one option
from a set.
RadioButton Attributes
Following are the important attributes related to RadioButton control.
Attribute Description
android:text This is the Text to display.
android:baselineAlignBottom If true, the image view will be baseline aligned with based on its
bottom edge.
android:background This is a drawable to use as the background.
android:onClick This is the name of the method in this View's context to invoke when
the view is clicked.
android:visibility This controls the initial visibility of the view.
RadioGroup
A RadioGroup class is used for set of radio buttons. If we check one radio button that belongs to a radio
group, it automatically unchecks any previously checked radio button within the same group.
CHAPTER
15
Event Handling
E vents are a useful way to collect data about a user's interaction with interactive components of
your app, like button presses or screen touch etc. The Android framework maintains an event queue
into which events are placed as they occur and then each event is removed from the queue on a first-in,
first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per
requirements.
There are following three concepts related to Android Event Management:
Event Listeners: The View class is mainly involved in building up an Android GUI, same View class
provides a number of Event Listeners. The Event Listener is the object that receives
notification when an event happens.
Event Listeners Registration: Event Registration is the process by which an Event Handler gets
registered with an Event Listener so that the handler is called when the
Event Listener fires the event.
Event Handlers: When an event happens and we have registered and event listener foe the event, the
event listener calls the Event Handlers, which is the method that actually handles the
event.
Event Listeners & Event Handlers
Event Handler Event Listener & Description
onClick() OnClickListener()
This is called when the user either clicks or touches or focuses upon any widget like
button, text, image etc. You will use onClick() event handler to handle such event.
onLongClick() OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget like
button, text, image etc. for one or more seconds. You will use onLongClick() event
handler to handle such event.
onFocusChange() OnFocusChangeListener()
This is called when the widget loses its focus i.e. user goes away from the view item.
You will use onFocusChange() event handler to handle such event.
onKey() OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a
hardware key on the device. You will use onKey() event handler to handle such
event.
onTouch() OnTouchListener()
This is called when the user presses the key, releases the key, or any movement
gesture on the screen. You will use onTouch() event handler to handle such event.
onMenuItemClick() OnMenuItemClickListener()
This is called when the user selects a menu item. You will use onMenuItemClick()
event handler to handle such event.
There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc which may be needed for your application. So I recommend to refer official
documentation for Android application development in case you are going to develop a sophisticated
apps.
Event Listeners Registration:
Event Registration is the process by which an Event Handler gets registered with an Event Listener so
that the handler is called when the Event Listener fires the event. Though there are several tricky ways
to register your event listener for any event, but I'm going to list down only top 3 ways, out of which you
can use any of them based on the situation.
Using an Anonymous Inner Class
//--- find both the buttons---
Button sButton = (Button) findViewById([Link].button_s);
16
Notifications
A ndroid Toast class provides a handy way to show users alerts but problem is that these alerts are
not persistent which means alert flashes on the screen for a few seconds and then disappears. For
important messages to be given to the user, it is required to have more persistent method. Anotification
is a message you can display as an icon at the top of the device which we call notification bar or status
bar.
Create and Send Notifications
You have simple way to create a notification. Follow the following steps in your application to create a
notification:
STEP 1 - CREATE NOTIFICATION BUILDER
As a first step is to create a notification builder using [Link](). You will use
Notification Builder to set various Notification properties like its small and large icons, title, priority etc.
[Link] mBuilder = new [Link](this)
You have plenty of optional properties which you can set for your notification. To learn more about
them, see the reference documentation for [Link].
STEP 3 - ATTACH ACTIONS
This is an optional part and required if you want to attach an action with the notification. An action
allows users to go directly from the notification to an Activity in your application, where they can look at
one or more events or do further work. The action is defined by a Pending Intent containing an Intent
that starts an Activity in your application. To associate the Pending Intent with a gesture, call the
appropriate method of [Link]. For example, if you want to start Activity when the
user clicks the notification text in the notification drawer, you add the Pending Intent by calling
setContentIntent().
A Pending Intent object helps you to perform an action on your application’s behalf, often at a later
time, without caring of whether your application is running or not.
We take help of stack builder object which will contain an artificial back stack for the started Activity.
This ensures that navigating backward from the Activity leads out of your application to the Home
screen.
Intent resultIntent = new Intent(this, [Link]);
TaskStackBuilder stackBuilder = [Link](this);
[Link]([Link]);
// Adds the Intent that starts the Activity to the top of the stack
[Link](resultIntent);
PendingIntent resultPendingIntent = [Link]( 0,
PendingIntent.FLAG_UPDATE_CURRENT );
[Link](resultPendingIntent);
If you want that your application support back to main activity while pressing back button, then add the
following in [Link]:
<activity android:name=".secondActivity"
android:label="Details of second activity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="[Link].PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
CHAPTER
17
Android Alert Dialogs
S ome times in your application, if you wanted to ask the user about taking a decision between yes
or no in response of any particular action taken by the user, by remaining in the same activity and
without changing the screen, you can use Alert Dialog.
In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner class
of AlertDialog. Its syntax is given below
[Link] alertDialogBuilder = new [Link](this);
Now you have to set the positive (yes) or negative (no) button using the object of the
AlertDialogBuilder class. Its syntax is:
[Link](CharSequence text, [Link] listener)
[Link](CharSequence text, [Link] listener)
Apart from this, you can use other functions provided by the builder class to customize the alert dialog.
These are listed below:
Method type & description
setIcon(Drawable icon)
This method set the icon of the alert dialog box.
setCancelable(boolean cancelable)
This method sets the property that the dialog can be cancelled or not.
setMessage(CharSequence message)
This method sets the message to be displayed in the alert dialog.
setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems,
[Link] listener)
This method sets list of items to be displayed in the dialog as the content. The selected option will be
notified by the listener.
setOnCancelListener([Link] onCancelListener)
This method Sets the callback that will be called if the dialog is canceled.
[Link] setDefaults (int defaults)
Set the default notification options that will be used.
setTitle(CharSequence title)
This method set the title to be appear in the dialog
After creating and setting the dialog builder, you will create an alert dialog by calling the create()
method of the builder class. Its syntax is:
AlertDialog alertDialog = [Link]();
[Link]();
Example:
[Link] alertDialogBuilder = new [Link](this);
[Link]([Link]);
[Link]([Link].positive_button,
new [Link]() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Intent positveActivity = new
Intent(getApplicationContext(),[Link]);
startActivity(positveActivity);
}
});
[Link]([Link].negative_button,
new [Link]() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent negativeActivity = new
Intent(getApplicationContext(),[Link]);
startActivity(negativeActivity);
}
});
AlertDialog alertDialog = [Link]();
[Link]();
Let's try to run Application we just modified, I assume you had created your AVD while doing
environment setup. To run the app from android studio click run icon and you application will be opened
in your running virtual device.
CHAPTER
18
Android SQLite Database
S QLite is an open source SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you don't need to
establish any kind of connections for it like JDBC, ODBC etc.
Database – Package
The main package is [Link] that contains the classes to manage your own databases.
Database – Creation
In order to create a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter.
It returns an instance of SQLite database which you have to receive in your own object. Its syntax is
given below.
SQLiteDatabse mydatabase = openOrCreateDatabase ("your database name”, MODE_PRIVATE, null);
Apart from this, there are other functions available in the database package that does this job. They are
listed below:
Method type & description
openDatabase(String path, [Link] factory, int flags, DatabaseErrorHandler
errorHandler)
This method only opens the existing database with the appropriate flag mode. The common flags mode
could be OPEN_READWRITE, OPEN_READONLY.
openDatabase(String path, [Link] factory, int flags)
It is similar to the above method as it also opens the existing database but it does not define any
handler to handle the errors of databases.
openOrCreateDatabase(String path, [Link] factory)
It not only opens but create the database if it not exists. This method is equivalent to openDatabase
method.
openOrCreateDatabase(File file, [Link] factory)
This method is similar to above method but it takes the File object as a path rather than a string. It is
equivalent to [Link]().
Database – Insertion
We can create table or insert data into table using execSQL method defined in SQLiteDatabse class. Its
syntax is given below:
[Link]("CREATE TABLE IF NOT EXISTS users(Username VARCHAR,Password VARCHAR)");
[Link]("INSERT INTO users VALUES('admin','admin')");
This will insert some values into our table our database.
We have another method that also does the same job but takes some additional parameter:
execSQL(String sql, Object[] bindArgs)
This method not only insert data, but also used to update or modify already existing data in database
using bind arguments.
Database – Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a method of this
class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move
the cursor forward and retrieve the data.
Cursor resultSet = [Link]("Select * from users",null);
While([Link]())
{
[Link]();
String username = [Link](1);
String password = [Link](2);
}
There are other functions available in the Cursor class that allows us to effectively retrieve the data.
Method type & description
getColumnCount()
This method return the total number of columns of the table.
getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column.
getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column.
getColumnNames()
This method returns the array of all the column names of the table.
getCount()
This method returns the total number of rows in the cursor.
getPosition()
This method returns the current position of the cursor in the table
isClosed()
This method returns true if the cursor is closed and return false otherwise.
Database - Helper class
For managing all the operations related to the database, a helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and updating of the database.
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion){}
}
Example:
The following SQLite Database helper class will handle the insertion and selection of users profile table:.
public class Database extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "[Link]";
public static final String TABLE_NAME = "profile";
public static final String COLUMN_ID = "id";
public static final String COLUMN_FNAME = "fname";
public static final String COLUMN_LNAME = "lname";
public static final String COLUMN_PHONE = "phone";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
[Link]("CREATE TABLE "+TABLE_NAME+" IF NOT EXISTS("+COLUMN_ID+" integer primary key, "+
COLUMN_FNAME+" text,"+
COLUMN_LNAME+" text,"+
COLUMN_PHONE+" text,"+
COLUMN_EMAIL+" text,"+
COLUMN_PASS+" text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
[Link]("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insert (String fname, String lname, String phone, String email, String password)
{
SQLiteDatabase db = [Link]();
ContentValues contentValues = new ContentValues();
[Link]("fname", fname);
[Link]("lname", lname);
[Link]("phone", phone);
[Link]("email", email);
[Link]("password", password);
[Link](TABLE_NAME, null, contentValues);
return true;
}
19
Android PHP/MySQL
I n this chapter, we are going to explain, how you can integrate PHP and MYSQL with your android
application.
This is very useful in case you have a webserver, and you want to access its data on your android
application. MYSQL is used as a database at the webserver and PHP is used to fetch data from the
database. Our application will communicate with the PHP page with necessary parameters and PHP will
contact MYSQL database and will fetch the result and return the results to us.
PHP – PDO (MYSQL)
CREATING DATABASE
<?php
define("HOST","localhost");
define("DBNAME","dbname");
define("USER","root");
define("PASS","");
class connection
{
public $con;
function __construct()
{ $this->conenct(); }
private function conenct()
{
$this->con = new PDO("mysql:host=".HOST.",USER,PASS);
// Create Database if not exists
$query = "CREATE DATABASE IF NOT EXISTS".DBNAME;
$result = $this->con->prepare($query);
$isCreated = $result->execute();
if($isCreated)
{
$this->con = new PDO("mysql:host=".HOST.;DBNAME=".DBNAME,USER,PASS);
echo "Database Created";
}
else{ echo "Error, while creating database";}
}
CREATING TABLES
Once database is created, it’s time to create some tables in the database. The CREATE TABLE statement
creates the database.
<?php
define("HOST","localhost");
define("DBNAME","users");
define("USER","root");
define("PASS","");
class connection
{
public $con;
function __construct()
{ $this->conenct(); }
private function conenct()
{
$this->con = new PDO("mysql:host=".HOST,USER,PASS);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
// Create Database if not exists
$query = "CREATE DATABASE IF NOT EXISTS ".DBNAME;
$result = $this->con->prepare($query);
$isCreated = $result->execute();
if($isCreated > 0)
{
$this->con = new PDO("mysql:host=".HOST.";dbname=".DBNAME,USER,PASS);
echo "Database Created<br/>";
$this->createTable();
}
else{
echo "Error, while creating database<br/>";
}
$this->con = null;
}
private function createTable()
{
$this->con = new PDO("mysql:host=".HOST.";dbname=".DBNAME,USER,PASS);
// Create Database if not exists
$query = "CREATE TABLE IF NOT EXISTS profile(id int primary key auto_increment,
fname text,lname text,phone NVARCHAR(64),email VARCHAR(200),
password NVARCHAR(400))";
$result = $this->con->prepare($query);
$res = $result->execute();
if($res > 0)
{ echo "Table Created<br/>"; }
else{ echo "Error, while creating table<br/>"; }
}
FUNCTIONS FOR INSERTING AND SELECTING VALUES FROM TABLES
Add the two following function in your PHP database helper class to insert and select values:
if(is_null($param))
{
$result = $this->con->prepare($query);
return $result->execute();
}
else
{
$result = $this->con->prepare($query);
return $result->execute($param);
}
if(is_null($param))
{
$Q2 = $this->con->prepare($query);
$Q2->execute();
return $Q2;
}
else
{
$Q2 = $this->con->prepare($query);
$Q2->execute($param);
return $Q2;
}
}
ANDROID - CONNECTING MYSQL
[Link](true);
[Link](true);
OutputStream os = [Link]();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
[Link](query);
[Link]();
[Link]();
[Link]();
[Link]();
if(response_code == HttpURLConnection.HTTP_OK)
{
// Read Data Sent from server
InputStream input = [Link]();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
ret = [Link]();
}
Note:
While working with database it’s recommended to use AsyncTask which allows us to run our database
queries in the background which can accelerate the security and performance of our application.
public class RegisterActivity extends AsyncTask<String,String,String>{
protected void onPreExecute(){
}
@Override
protected String doInBackground(String... arg0) {
/* all you database queries here
* insert query
* delete query
* update query
* select query
* res = result returned from database
*/
}
@Override
protected void onPostExecute(String result){
//after database query successfully run or failed
}
}
Example:
@Override
protected String doInBackground(String... strings) {
String ret = "";
String link = "[Link]
try{
url = new URL(link);
}
catch (MalformedURLException e)
{
[Link]();
ret = "URL Exception";
}
try{
conn = (HttpURLConnection) [Link]();
[Link](READ_TIMEOUT);
[Link](CONNECTION_TIMEOUT);
[Link]("POST");
[Link](true);
[Link](true);
OutputStream os = [Link]();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
[Link](query);
[Link]();
[Link]();
[Link]();
[Link]();
}
catch(IOException IOe)
{
[Link]();
ret = "2nd Exception";
}
try{
int response_code = [Link]();
catch(IOException IOe)
{
[Link]();
ret = "2nd Exception";
}
try{
int response_code = [Link]();
if(response_code == HttpURLConnection.HTTP_OK)
{
// Read Data Sent from server
InputStream input = [Link]();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
ret = [Link]();
}
}
catch (IOException IOe2)
{
[Link]();
ret = "3rd Exception";
}
finally {
[Link]();
}
result = ret;
return ret;
}
@Override
protected void onPostExecute(String s) {
[Link](s);
[Link](getApplicationContext(),result,Toast.LENGTH_LONG).show();
[Link](result);
}
}
Content of [Link]
<uses-permission android:name="[Link].ACCESS_NETWORK_STATE" />
<uses-permission android:name="[Link]"/>