Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 51

IMPORTANT NOTES

Mobile Application Development

Introduction to Android
Android is an operating system which is based on the Linux kernel. Android
system is also called as Android Open Source Project (AOSP), lead by
Google. Android is used for mobile devices, such as smart phones and tablet
computers. The Android application makes life more comfortable and
advanced for the users.

Features of Android

The above diagram shows some features of Android:

 Android is a powerful, open source, Linux – based operating system.


 It provides a rich development environment for building the
applications.
 Android has a higher success ratio, because it reduces the
development cost.
 Android has a large developer community which integrates the internal
application.
 It has reached the top of the smart phone market segment and day by
day its user base is growing strong.
 Android supports audio, video formats like JPEG, PNG, GIF, BMP, MP3,
MP4, MIDI, AMR, AMR-WB, MPEG-4 etc.

pg. 1
Android Version Description

Android 1.6 Donut This version comes in all shapes and sizes. It allows Android to run on a variety of
IMPORTANT NOTES
screen resolutions Mobile
and aspect ratios.
Application Development

It has a quick search box that searches the result from the web, from your phone's
local content all at once from a single box on the home screen.

Android 2.1 Eclair This version provides Google map navigation. For example, in car navigation
system, a forward looking 3D view, voice guidance and traffic information all for
free.

It provides customized ring tones, wallpapers and ability to arrange apps


(applications) and widgets across multiple screens and in folders. The 'Speech-to-
text' is introduced in this version where your spoken words appear straight on your
screen.

Android 2.2 Froyo This version provides voice capabilities which let you perform key functions on your
phone like searching, getting directions, making notes, setting alarms and more with
just the sound of your voice.

It provides portable Wi-Fi hotspot into your phone where you could stay connected
even when on the go.

Android 2.3 This version provides gaming APIs. It builds rich, graphics-intensive 3D games. This
Gingerbread version introduces NFC (Near Field Communication) which supports to transmit the
information between devices just by bringing them close together.

This version displays how much battery of your device has been consumed, allows
you to adjust the screen brightness, find out the active applications.

Android 3.0 This version introduces tablet-friendly design with a larger layout pattern. It
Honeycomb enhances the experience of reading books, watching videos, exploring maps and
more.

It provides a new system bar which is enabled on-screen navigation that controls
your Android device. This version gives rights to the user to access essential
information easily like time, date, battery life and connection status of your device
all in one place.

Android 4.0 Ice This version provides Widgets which embed live app content directly on your home
Cream Sandwich screen that becomes more flexible to customize the home screen.

It manages the network data usage. It tracks how much data you used, set warning
levels and hard limits and disable your service if you reach the limit.

Android 4.1 Jelly This version provides actionable notifications which take action directly from the
Bean notification.

It enables multiple users on one device. It provides an account switching feature


where each account has its own customized space from the home screen to
wallpaper, widgets and apps, so user can share a device and not his/her information.

Android 4.4 KitKat This version helps to get the things done without touching the mobile screen, just
with the sound of your voice – just say “OK Google” to launch voice search, send a
pg. 2
text, get directions or even play a song.
IMPORTANT NOTES
Mobile Application Development

History of Android

 Android was developed by the Open Handset Alliance, led by


Goggle.
 The first version of Android was released by Google in 2007 and the
Android version 1.0 was released in September 2008.
 In June 2012, Google announced the next Android version 4.1 Jelly
Bean. This version of Android is an incremental update which is
mostly used for improving the user interface.

Advantages of Android

 Android is largely supported by Google allowing you to use various


services of Google.
 Android is an open source and runs on mobile devices, tablets etc.
 It is multitasking that means you can run many applications at the
same time. For example, you can browse Facebook while listening the
song.
 The Android operating system is available on mobile phones from
various manufacturers like Samsung, Motorola, HTC, Sony Ericsson
etc.
 Using Android phone, you can easily check e-mail from Gmail if your
Gmail account is integrated with Google Services.
 User can easily access a variety of settings quickly and easily.

Disadvantages of Android

 Android requires continuous Internet connection if you are using


Google services.
 Android shows error & forces to close the large apps/games, which is
very annoying.
 It takes large amount of mobile data if a large number of background
processes are running.
 It increases the usage of RAM and decreases battery performance
when many processes are running in the background.

Android Application Components

pg. 3
IMPORTANT NOTES
Mobile Application Development

 Application components are the essential part of the Android operating


system which is used to build the Android applications.
 The AndroidManifest.xml file describes each component of the
application and how they interact.
Following are the Android Application Components,
1. Activities
2. Services
3. Content Providers
4. Broadcast Receivers
5. Intents

1. Activities
 Activity is also known as Widgets.
 Activity represents a single screen with a user interface.
 It is an individual user interface screen in an Android Application
where visual elements called Views.
 It interacts with the user to do only one thing, such as unlock screen,
dial a phone, etc.
 If new activity starts, then previous activity is stopped, but the data is
preserved.
 An application consists of multiple activities.
For example, an email application has one activity to display a list of
new emails, another activity is to compose email, reading email and
so on.
2. Services
 Services performs the action without user interaction in the
background, but does not get initiated without user invocation.
 It does not require a user interface.
 It is an android application component which runs in a background and
has no visual UI.
 It is used to perform the processing part of your application in the
background.
For example, music player application. When the music station is
playing the song, the user can open another application and the song
plays in the background.
3. Content Providers
 Content providers are the android application component that provide
a flexible way to make data available across applications.

pg. 4
IMPORTANT NOTES
Mobile Application Development

 It manages common data based on permissions.


 It manages the data which is being shared by more than one
application.
 Content provider is a critical concept that has led to develop in-house
android applications in a better way.
4. Broadcast Receivers
 Broadcast receivers are used to receive messages which are broadcast
by the Android applications.
For example, the warning where the battery is getting low, change
of time zone, etc.
They respond to broadcast messages from other applications.
5. Intent
 Intent is a message which allows components to request activities
from other components.
There are two types of Intents,
1. Explicit Intents
2. Implicit Intents

1. Explicit intents are used for application's internal communications.

2. Implicit intent means sending a message to the Android system to find a


suitable activity that can be responded to the intent.

Android Architecture:-
Android architecture is a stack of software components. It is in the form of a
software application, operating system, run-time environment, middleware,
native libraries and services.

It is categorized into five parts as below:


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

Each part of the stack and the elements within each layer are integrated and
provide optimal application development and execution environment for
mobile devices.

The following diagram shows the architecture of Android,

pg. 5
IMPORTANT NOTES
Mobile Application Development

1. Linux Kernel
 Linux is the heart of Android architecture.
 It provides a level of abstraction between the hardware devices and
the upper layers of the Android software stack.
 The Android operating system is based on the Linux kernel.
 The Linux kernel is responsible for various device drivers such as
Camera driver, Display driver, Bluetooth driver, Keypad driver,
Memory management, Process management, Power management,
etc.
2. Native Libraries
 The native libraries such as Media, WebKit, SQLite, OpenGL, FreeType,
C Runtime library (libc) etc. are situated on the top of a Linux kernel.
 Media library is responsible for playing and recording audio and video
formats, FreeType is for font support, WebKit is for browser support,
SQLite is for database, SSL is for Internet security etc.
3. Android Runtime
 Android Runtime is the third section of the architecture and situated
on the second layer from the bottom.
 Android Runtime includes core libraries and Dalvik Virtual Machine
(DVM) which is responsible to run android application.
 Dalvik Virtual Machine (DVM) is like Java Virtual Machine (JVM) in
Java, but DVM is optimized for mobile Devices.

pg. 6
IMPORTANT NOTES
Mobile Application Development

 DVM makes use of the Linux core features like memory management
and multi-threading, which are essential in the Java language.
 DVM provides fast performance and consumes less memory.
4. Application Framework
 Application framework is situated on the top of the Native libraries and
Android runtime.
 Android framework provides a lot of classes and interfaces for Android
application development and higher level services to the applications
in the form of Java classes.
 It includes Android API's such as Activity manager, Window manager,
Content Provider, Telephony Manager, etc.
 Activity manger is responsible for controlling all the aspects of the
application lifecycle and activity stack, Content provider is responsible
for allowing the applications to publish and share the data with the
other applications, View system is responsible for creating application
user interfaces, etc.
5. Applications
 Applications are situated on the top of the Application framework.
 The applications such as Home, Contact, Alarm, Calender, Camera,
Browsers, etc. use the Android framework which uses Android runtime
and libraries. Android runtime and Native libraries use Linux kernel.
 The user can write his/her application to be installed on this layer only.

Android Activity Lifecycle


Android Activity Lifecycle is a collection of methods exposed within the
Activity class which provides the developer a resource management
framework. The resource management framework allows developers to meet
the unique state management requirements of each activity and handle the
resource management.

pg. 7
IMPORTANT NOTES
Mobile Application Development

This lifecycle is controlled by seven methods of android.app.Activity.class.


This activity is the subclass of ContextThemeWrapper class.

 An Activity is a screen which contains the user interface.


 User can interact with these activities to perform some task such as
send an email, send messages or taking the photo.

pg. 8
IMPORTANT NOTES
Mobile Application Development

 The above figure shows the seven methods of an Android activity


lifecycle. When you run your application, an Activity goes through the
different states.
 These seven activities describes how activity will behave at different
states.
 The main purpose of an activity is to interact with the user.
 It is the single screen in android and is like a window or frame of Java.
 With the help of activity, user can place all the UI components or
widgets in a single screen.
Following are the seven callback methods of Android Activity
Lifecycle which are called by the system,

1. OnCreate()
2. OnStart()
3. OnResume()
4. OnPause()
5. OnStop()
6. OnRestart()
7. OnDestroy()

Activity Description
Methods

OnCreate() This method is called when activity is created. It is used to initialize the activity.

It takes a 'Bundle' parameter which is used for storing and passing state information
and objects between activities.

OnStart() This method is called when activity becomes visible to the user.

It is called by the system after OnCreate() method is finished.

OnResume() This method is called when activity will start interacting with the user.

It is used to initialize fields, register listeners, bind to services etc.

OnPause() This method is called when current activity is being paused and the previous activity is
being resumed.

Activity is not destroyed and not visible to the user. It is used to release resources or
save application data.

OnStop() This method is called when activity is no longer visible to the user.

OnRestart() This method is called after your activity has stopped and restarting.

pg. 9
IMPORTANT NOTES
Mobile Application Development

OnDestroy() This method is called before the activity is destroyed.

States of an Activity

Activity Description
State

Running This state defines that the activity is visible and interacts with the user.

Paused This state defines that the activity is still visible but partially hidden and the instance is
running but might be killed by the system.

Stopped This state defines that the activity is not visible and the instance is running but might be
killed by the system.

Killed This state defines that the activity has been terminated by the system call to its finish()
method.

Android Programing Structure


Developing an Android project, you have to install the Android plug-ins for
Eclipse and at least have some knowledge of Java programming.

After installing all the plug-ins for an Android file, you can begin to develop
an Android application.

Android uses packages not only to arrange the code in an application but to
manage the application themselves.

pg. 10
IMPORTANT NOTES
Mobile Application Development

pg. 11
IMPORTANT NOTES
Mobile Application Development

pg. 12
Folder Name Description

src The 'src' stands for Source Code.NOTES


IMPORTANT It contains the Java Source files.
Mobile Application Development
gen The 'gen' stands for Generated Java Library. This library is for Android internal
use only.

Android 2.2 The Android Framework Library is stored here.

assets It is used to store raw asset files.

libs It contains private libraries.

res The 'res' stands for Resource file. It can store resource files such as pictures,
XML files, etc. It contains some additional folders such as Drawable, Layout and
Values.

anim: It is used for XML files that are compiled into animation objects.
color: It is used for XML files that describe colors.
drawable: It is used to store various graphics files. In Android project structure,

there are three types of drawable folders,


1. drawable-mdpi
2. drawable-hdpi
3. drawable-ldpi

The above drawable folders are required in order to adapt to different screen
resolutions.

layout: It is used for placing the XML layout files, which defines how various
Android objects such as textbox, buttons, etc. are organized on the screen.

menu: It is used for defining the XML files in the application menu.

raw: The 'raw' stands for Raw Asset Files. These files are referenced from the
application using a resource identifier in the R class.
For example, good place for media is MP3 or Ogg files.

values: It is used for XML files which stores various string values, such as titles,
labels, etc.

xml: It is used for configuring the application components.

AndroidManifest.xm This file indicates the Android definition file. This file contains the information
l about the Android application such as minimum Android version, permission to
access Android device capabilities such as Internet access permission, phone
permission etc.

default.properties This file contains the project settings, such as build the target. Do not edit this file
manually. It should be maintained in a Source Revision Control System.

Proguard.cfg This file defines how ProGuard optimizes and makes your code unclear.

MainLayout.xml This file describes the layout of the page. So all the components such as
textboxes, labels, radio buttons, etc. are displaying on the application screen.

Activity class
pg. 13 The application occupies the entire device screen which needs at least one class
inherits from the Activity class. OnCreate() method initiates the application and
loads the layout page.
IMPORTANT NOTES
Mobile Application Development

The above diagram shows the basic building blocks of an Android


application. Android application in Eclipse or in any development tool have a
pre-defined structure with code and resource organized into a number of
folders.

Every Android project contains several folders, like:

What is SQLite?
SQLite is an open source database. It supports standard relational database
features like SQL syntax, transactions, prepared statement, etc. It has
methods to create, delete, execute SQL commands and perform other
common database management tasks.

SQLite supports following datatypes:

Datatype Description

TEXT It is similar to String in Java.

INTEGER It is similar to Long in Java.

REAL It is similar to Double in Java.

SQLite in Android

 Android does not require a setup procedure or administration of the


database using an SQLite database.
 SQLite database is embedded in every Android device.
 It stores data to a text file on a device and supports all the relational
database features.
 To use the SQLite database, the SQLiteOpenHelper class is used which
provides various functionality.

SQLite Database Architecture

Package The android.database.sqlite is the main package in Android SQLite which contains
the classes to manage your own databases.

pg. 14
IMPORTANT NOTES
Mobile Application Development

Creation The openOrCreateDatabase() method is called for creating a database with your
database name and mode as a parameter.
This method returns an instance of SQLite database.

Syntax
SQLiteDatabse mydatabase = openOrCreateDatabase (“database_name”,
MODE_PRIVATE, null);

Insertion The execSQL() method is used to insert the data into table. This method is defined
in SQLiteDatabse class.

Syntax:
execSQL(String SQL, Object[] bind Args)

The execSQL() method is used not only to insert a data, but also to update or
modify the existing data in database, using bind arguments.

Example:

mydatabase.execSQL(“CREATE TABLE TutorialRide(Admin_name VARCHAR,


Password VARCHAR);”);

mydatabase.execSQL(“INSERT INTO TutorialRide VALUES('ABC', '123');”);

Fetching An object of the Cursor class is used to fetch the data from the database. Calling a
method of Cursor class is called rawQuery which returns a resultset with the
cursor pointing to the table.
The rawQuery() accepts an SQL SELECT statement as an input.

Example:

Cursor resultset = mydatabase.rawQuery(“SELECT * FROM Employee”, null);

resultset.moveToFirst();

String eid = resultset.getString(1);


String ename = resultset.getString(2);

SQLiteOpenHelper This class is used for creating a database and version management.
Class
In this class, there are two methods which need to override for creating and
updating the database, they are onCreate() and onUpgrade().

If the database is accessed but not yet created then onCreate() method is called
by the framework.

pg. 15
IMPORTANT NOTES
Mobile Application Development

If the database version is increased in your application code


then onUpgrade() method is called. It allows to modify the exisitng database.

The SQLiteOpenHelper class provides


the getReadableDatabase() and getWriteableDatabase() methods to get
access to an SQLiteDatabase object.

Following are the data storage options


1. Shared Preferences
2. Internal Storage
3. External Storage
4. SQLite Database
5. Network Connection

Internal storage helps users to save or read their data from the device
Internal memory. The FileInputStream and FileOutputStream classes are
used to read and write data into the file.

A. Write Operation
The openFileOutput() method is called for writing the data in the file using
Internal storage. It takes two parameters. First parameter is the file name
and second one is file mode.

Syntax:
FileOutputStreamfopStream = openFileOutput(“file_name”, MODE_PRIVATE);

pg. 16
IMPORTANT NOTES
Mobile Application Development

Example

String str = “TutorialRide”;


fopStream.write(str.getBytes());
fopStream.close();

B. Read Operation
The openFileInput() method is called for reading the data from file with the
name of the file. It takes one parameter as file name. The file name should
be same as you have written in the openFileOutput() method. It returns an
instance of FileInputStream class.

Example

int read = -1;


StringBuffersb = newStringBuffer();
FileInputStreamfipStream = openFileInput(“file_name”);
while((read = fibStream.read()) != -1)
{
sb.append((char)read);
}

1. Shared Preference

 The SharedPreferences class is used to store the private primitive


data (such as int, float, boolean, long and string) in key-value pairs.
 This class provides a general framework which allows to save and
retrieve persistent key-value pairs of primitive data types.
 The getSharedPreferences() and getPreferences() methods are
used to get a SharedPreferences object for the application.
 The getSharedPreferences() method is used when user needs
multiple preferences file which is identified by name.
 The getPreferences() method is used when user needs only one
preferences file for his/her activity. Because this will be the only
preferences file for Activity which don't supply a name.

2. Internal Storage

pg. 17
IMPORTANT NOTES
Mobile Application Development

 Internal storage is used to store private data on the device memory.


 This storage enables you to read and write data into files that are
associated with each application's internal memory.
 By default, the user can save the files to the internal storage which are
private to the application. Neither other applications nor the user can
access these files.
 When the user uninstalls the application, these files are removed from
the device memory.
 When users use MODE-PRIVATE for files on the internal storage,
they are never accessible to the other applications.
The other modes are
i) MODE_APPEND
ii) MODE_WORLD_READABLE
iii) MODE_WORLD_WRITEABLE

3. External Storage

 External storage is used to store public data on the shared external


storage.
 This storage can be removable storage media such as an SD card or
an internal (non-removable) storage.
 The user can read and modify the files if they are stored in the
external storage.
 The READ_EXTERNAL_STORAGE or
WRITE_EXTERNAL_STORAGE is used to acquire the system
permissions to read or write the files on the external storage.
 The WRITE_EXTERNAL_STORAGE permission is used when the user
needs both read and write files, because it implicitly requires read
access as well.

4. SQLite Database

 SQLite database is used to store the structured data in a private


database.
 The database will be accessible by its name to any class in the
application, but not outside the application.
 Android provides full support to SQLite databases.

pg. 18
IMPORTANT NOTES
Mobile Application Development

 The SQLiteOpenHelper class is used for creating a database and


version management. This class includes two methods onCreate() and
onUpgrade() for creating and updating the database.

5. Network Connection

 Network Connection is used to store the data on the web with your
own network server.
 The user can use the network connection when it's available to store
and retrieve the data on your own web-based services.

The following packages are used with the classes for


performing the network connection
1. Java.net.*
2. android.net.*

 The Java.net.* package provides the classes for implementing the


networking applications.

This package is divided into two sections,


i. Low Level API deals with addresses, sockets and interfaces.
ii. High Level API deals with URIs, URLs and connections.

 The android.net.* package classes provide network access, beyond


the normal java.net.* APIs.
Example : Android Internal Storage

Following internal storage example demonstrates, how the user's data is


stored into an Android internal memory.

Write Operation

File name: activity_main.xml

What are events in android?


Events are the messages or notifications which are generated by controls
such as buttons, checkbox, radio buttons etc. System responds to those
messages or notifications by executing some code.

pg. 19
IMPORTANT NOTES
Mobile Application Development

Following are the three concepts related to Android Event


Management,

1. Event Listener contains a single callback method. It is an interface in the


View class.
2. Event Handler is the method that handles the event. The Event Listener
calls the Event Handlers.
3. Event Listener Registration is a process, where an Event Handler gets
registered with an Event Listener. Event Handler is called when the Event
Listener fires the event.

Following are the Event Handlers and Event Listeners that handle the
user's interaction with interactive components of Application

Event Handler Event Listener Description

onClick() OnClickListener() Called when the user either clicks or


touches any widget like button, images,
text etc.

onLongClick() OnLongClickListener() Called when the user either clicks or


touches any widget like button, text,
image etc. for one or more seconds.

onFocusChange() OnFocusChangeListener() Called when the widget looses its focus


that means the user goes away from the
view point.

onKey() OnFocusChangeListener() Called when the user is focused on the


item and presses or releases a key on
the device.

onTouch() OnTouchListener() Called when the user presses or releases


the key.

onMenuItemClick() OnMenuItemClickListener() Called when the user selects a menu


item.

OnCreateContextMenu() OnCreateContextMenuITemListener( Called when the context menu is being


) built.

What is Context in Android?


Android Applications are popular for a long time and it is evolving to a greater level
as users’ expectations are that they need to view the data that they want in an easier

pg. 20
IMPORTANT NOTES
Mobile Application Development

smoother view. Hence, the android developers must know the important terminologies
before developing the app. In Android Programming we generally come across the
word Context. So what exactly is this Context and why is it so important? To answer
this question let’s first see what the literal meaning of Context is:
The Circumstances that form the setting for an Event, Statement, or Idea, and in terms
of which it can be fully understood.
Looking at this definition we come across two things:
 The Context tells us about the surrounding information.
 It is very important to understand the environment which we want to
understand.
Similarly when we talk about Android Programming Context can be understood as
something which gives us the Context of the current state of our application.
It allows us to access resources.

It allows us to interact with other Android components by sending

messages.
 It gives you information about your app environment.
The code has been given in both Java and Kotlin Programming Language
for Android.
Understanding Context by a Real World Example
Let’s a person visit a hotel. He needs breakfast, lunch, and dinner at a
suitable time. Except for these things there are also many other things, he
wants to do during his time of stay. So how does he get these things? He will
ask the room-service person to bring these things for him. Right? So here
the room-service person is the Context considering you are the single
activity and the hotel to be your app, finally, the breakfast, lunch &
dinner have to be the resources.
How Does this Work?
1. It is the Context of the current/active state of the application.
Usually, the app got multiple screens like display/inquiry/add/delete
screens(A general requirement of a basic app). So when the user is
searching for something, the Context is an inquiry screen in this case.
2. It is used to get information about the activity and application.
The inquiry screen’s Context specifies that the user is in inquiry activity, and
he/she can submit queries related to the app
3. It is used to get access to resources, databases, shared preferences,
etc.
Via Rest services, API calls can be consumed in android apps. Rest
Services usually hold database data and provide the output in JSON format
to the android app. The Context for the respective screen helps to get hold of
database data and the shared data across screens

pg. 21
IMPORTANT NOTES
Mobile Application Development

4. Both the Activity and Application classes extend the Context class.
In android, Context is the main important concept and the wrong usage of it
leads to memory leakage. Activity refers to an individual screen and
Application refers to the whole app and both extend the Context class.

Types of Context in Android


There are mainly two types of Context that are available in Android.
1. Application Context and
2. Activity Context

The Overall view of the App hierarchy looks like the following:

It can be seen in the above image that in “Sample Application”, the nearest
Context is Application Context. In “Activity1” and “Activity2”, both Activity
Context (Here it is Activity1 Context for Activity1 and Activity2 Context for
Activity2) and Application Context.The nearest Context to both is their
Activity Context only.
Application Context
This Context is tied to the Lifecycle of an Application. Mainly it is an
instance that is a singleton and can be accessed
via getApplicationContext().

pg. 22
IMPORTANT NOTES
Mobile Application Development

Android - Application Components


Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml 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 −

Sr.No Components & Description

Activities
1
They dictate the UI and handle the user interaction to the smart phone screen.

Services
2
They handle background processing associated with an application.

Broadcast Receivers
3
They handle communication between Android OS and applications.

Content Providers
4
They handle data and database management issues.

Activities
An activity represents a single screen with a user interface,in-short Activity performs actions
on the screen. 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 −
public class MainActivity extends Activity {
}

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.

pg. 23
IMPORTANT NOTES
Mobile Application Development

A service is implemented as a subclass of Service class as follows −


public class MyService extends 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 BroadcastReceiver class and each
message is broadcaster as an Intent object.
public class MyReceiver extends BroadcastReceiver {
public void onReceive(context,intent){}
}

Content Providers
A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. The data may be stored in
the file system, the database or somewhere else entirely.
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 {
public void onCreate(){}
}
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 −

S.No Components & Description

Fragments
1
Represents a portion of user interface in an Activity.

2 Views

pg. 24
IMPORTANT NOTES
Mobile Application Development

UI elements that are drawn on-screen including buttons, lists forms etc.

Layouts
3
View hierarchies that control screen format and appearance of the views.

Intents
4
Messages wiring components together.

Resources
5
External elements, such as strings, constants and drawable pictures.

Manifest
6 Configuration file for the application.

Android Intent Tutorial

Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.

It is generally used with startActivity() method to invoke activity, broadcast receivers


etc.

The dictionary meaning of intent is intention or purpose. So, it can be described as


the intention to do action.

The LabeledIntent is the subclass of android.content.Intent class.

Android intents are mainly used to:

pg. 25
IMPORTANT NOTES
Mobile Application Development

o Start the service


o Launch an activity
o Display a web page
o Display a list of contacts
o Broadcast a message
o Dial a phone call etc.

Types of Android Intents


There are two types of intents in android: implicit and explicit.

1) Implicit Intent
Implicit Intent doesn't specifiy the component. In such case, intent provides
information of available components provided by the system that is to be invoked.

For example, you may write the following code to view the webpage.

1. Intent intent=new Intent(Intent.ACTION_VIEW);


2. intent.setData(Uri.parse("http://www.javatpoint.com"));
3. startActivity(intent);
2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external
class to be invoked.

1. Intent i = new Intent(getApplicationContext(), ActivityTwo.class);


2. startActivity(i);

Top Android UI Controls that


you must know about!
Android UI Controls are those components of Android that are used to
design the UI in a more interactive way. It helps us to develop an

pg. 26
IMPORTANT NOTES
Mobile Application Development

application that makes user interaction better with the view components.
Android provides us a huge range of UI controls of many types such as
buttons, text views, etc.

As we know UI is the only thing that a user interacts with within an


Application. This is the reason that we make our Application look aesthetic
and, more and more connective. To do so, we need to add the UI controls or
we say Input controls in the respective application.

Check the Android Application Components you didn’t know about.


Moving forth we will see some important Android UI controls for our
applications:

 TextView
 EditText
 Button
 ImageButton
 ToggleButton
 RadioButton
 RadioGroup
 CheckBox
 AutoCompleteTextView
 ProgressBar
 Spinner
 TimePicker
 DatePicker
 SeekBar
 AlertDialog
 Switch
 RatingBar

Android UI Controls

pg. 27
IMPORTANT NOTES
Mobile Application Development

Now we’ll understand the different Android UI Controls one by one:

1. TextView
TextView is a UI Component that displays the text to the user on their
Display Screen.

We can create it in two ways:

XML file:
For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android= "http://schemas.android.com/apk/res/android"

<TextView

//attributes to describe it

/>

</LinearLayout>

Activity file:
In this, we declare it using the setText() method as follows:

setContentView(R.layout.activity_main);

LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);

TextView textview_name = new TextView(this);

textveiw_name.setText(“Hello I am Text View”);

pg. 28
IMPORTANT NOTES
Mobile Application Development

linearLayout.addView(textView);

There are various attributes to describe the TextView some of them are
named below:

Android: id – it is a unique id for the control.



 Android: width – It displays the exact width of the TextView.
 Android: height – It displays the exact height of the TextView.
 Android:textColor – It set the color of the text.
 Android: gravity – It is to align the TextView.
There are some more attributes the above are the major ones.

2. EditText
EditText is a user interface control that allows the users to enter some text.

We can create it in two ways:

XML file:
For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>

<EditText

//attributes

>

</LinearLayout>

Activity file:
In activity, we declare it using the getText() method as follows:

setContentView(R.layout.activity_main);

LinearLayout linearlayout_name = (LinearLayout) findViewById (R.id.LinearLayout) ;

EditText edittext_name = new EditText(this);

edittext_name.setHint(“Hello I am EditText”);

linearLayout.addView(edittext_name);

pg. 29
IMPORTANT NOTES
Mobile Application Development

3. Button
This is a UI that is used to perform some action as soon as the user clicks on
it.

We can create it in two ways:

XML file:
For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>

<Button

//attributes

/>

</LinearLayout>

Activity file:
In activity, we declare it programmatically as below:

setContentView(R.layout.activity_main);

LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);

Button btn_name = new Button(this);

btn_name.setText(“Hello I am Button”);

linearLayout.addView(btn_name);

4. ImageButton
It is the same as a Button but it’s used to display an image on the button to
perform an Action. In this, we need to give the source of the image so that
the system can load it.

We can create it in two ways:

XML file:
For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>

<ImageButton

pg. 30
IMPORTANT NOTES
Mobile Application Development

//other attributes...

android:src= “@drawable/add_icon”/>

</LinearLayout>

Activity file:
In the activity file, we declare it programmatically as below:

setContentView(R.layout.activity_main);

LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);

ImageButton btn_name = new Button(this);

btn_name.setImageResource(R.drawable.add_icon);

linearLayout.addView(btn_name);

5. ToggleButton
The toggle button displays the ON/OFF states of a button with a light
indicator.

We can create it in two ways:

XML file:
For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>

<ToggleButton

//attributes

android:checked="true"

android:textOff="OFF"

android:textOn="ON"/>

</LinearLayout>

Activity file:
In the activity file we declare it programmatically as below:

setContentView(R.layout.activity_main);

LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);

pg. 31
IMPORTANT NOTES
Mobile Application Development

ToggleButton tb_name = new ToggleButton(this);

tb_name.setTextOff("OFF");

tb_name.setTextOn("ON");

tb_name.setChecked(true);

linearLayout.addView(btn_name);

6. RadioButton
Radio button in Android is the one that has only two possible states, that
are either checked or unchecked. Initially, it is in the unchecked state, once
it’s checked it can’t be unchecked.

We can create it in two ways:

XML file:
For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>

<RadioButton

android:text="Radio button"

android:checked="true"/>

</LinearLayout>

Activity file:
In the activity file, we declare it programmatically as below:

setContentView(R.layout.activity_main);

LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);

RadioButton btn_name = new RadioButton(this);

btn_name.setText("Hello");

btn_name.setChecked(true);

linearLayout.addView(btn_name);

pg. 32
IMPORTANT NOTES
Mobile Application Development

7. RadioGroup
It’s a group of Radio buttons that are alike. In this, only one of all the
buttons can be chosen.

We can create it in two ways:

XML file:
For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>

<RadioGroup android:orientation="vertical">

<RadioButton android:text="Radio Button 1"/>

<RadioButton android:text="Radio Button 2"/>

<RadioButton android:text="Radio Button 3"/>

</RadioGroup>

</LinearLayout>

Activity file:
In the activity file, we declare it programmatically as below:

RadioButton rdb1,rdb2,rdb3;

@override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

rdb1 = (RadioButton)findViewById(R.id.rdb_1);

rdb2 = (RadioButton)findViewById(R.id.rdb_2);

rdb3 = (RadioButton)findViewById(R.id.rdb_3);

Button btn = (Button)findViewById(R.id.getBtn);

Above is the example to declare it, to make it functional, we would override


and define the methods that are required.

pg. 33
IMPORTANT NOTES
Mobile Application Development

8. CheckBox
A CheckBox is the UI control that has two states that are either checked or
unchecked. If we have a group of CheckBox, we can select as many as we
want, unlike RadioGroup.

We can create it in two ways:

XML file:
For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>

<CheckBox

android:checked="true"

android:text="CheckBox"

// other attributes

/>

</LinearLayout>

Activity file:
In activity, we declare it programmatically as below:

setContentView(R.layout.activity_main);

LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);

CheckBox cb_name = new CheckBox(this);

cb_name.setText("DataFlair");

cb_name.setChecked(true);

layout.addView(cb_name);

9. ProgressBar
In Android, we have a progress bar that shows the progress of some action
that is happening like pasting a file to some location. A progress bar can be
in two modes:

 Determinate Mode:

pg. 34
IMPORTANT NOTES
Mobile Application Development

In this, the progress is shown with the percent of action completed. Also,
the time to be taken is already determined.

 Indeterminate Mode:
In this, there is no idea of when the task would be completed, therefore, it
functions continuously.

We can create it in two ways:

XML file:
For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android=”http://schemas.android.com/apk/res/android”>

<ProgressBar

// attributes, here we define the speed, layout, id, etc.

/>

</LinearLayout>

Activity file:
In activity, we declare it programmatically as below:

setContentView(R.layout.activity_main);

pgsBar = (ProgressBar)findViewById(R.id.pBar);

txtView = (TextView)findViewById(R.id.tView);

Button btn = (Button)findViewById(R.id.btnShow);

Here we need to set the sleep time and override the onClick() and
onCreate() methods

The above were some of the very important UI controls, now we will also
read about some more UI controls :

1. Spinner
The Spinner in Android is a User Interface that is used to select a particular
option from a list of given options. Spinner in Android is the same as
dropdown in HTML. It provides us with a faster way to select an option of
our choice. When we click on the down arrow, it shows a list of values from

pg. 35
IMPORTANT NOTES
Mobile Application Development

which we can select one. By default, the first value would be shown as the
currently selected Value.
2. TimePicker
Time picker is a UI component that works as an intermediate to select a
time of the day. The time chosen by it is shown either in 24 hrs format or in
12hrs format using AM and PM.

It gives a virtual Clock/watch to select it. This virtual clock makes it easy to
choose the time.

3. DatePicker
Like we have time picker, we have a date picker as UI control too. In this,
the System shows a virtual calendar to the users to choose the day.

This enables the user to choose a particular date using either a calendar or a
dropdown. These both are made to make it easier for the user to pick up a
date and a time.

4. SeekBar
In Android, Seekbar is an extended Progress bar. A seekbar comes with a
pointer that is draggable throughout the bar either in left or right. This
pointer helps to set the progress as well. This helps the user to choose a
particular range of values.

5. RatingBar
A rating bar in Android is an extended version of a seekbar. It is used to
give the rating by touching it. In the rating bar, a user can rate at a scale of 5
with a difference of 0.5.

Its rating is in Stars. The user needs to tap/click the stars.

pg. 36
IMPORTANT NOTES
Mobile Application Development

6. AlertDialog
Alert Dialog Box is a UI that gives the users an Alert or Warning of
something. It appears on the screen in a small window. Once it comes, the
user needs to decide or choose an option that it shows.

For example, when you enter the wrong password for email id.

7. Switch
In Android, a switch is a two-state UI element that holds either ON or OFF
state. ON generally means Yes and OFF means No. By default, a switch is in
the OFF state. A user can change its state many times.

8. AutoCompleteTextView
AutoCompleteTextView is an extension of EditText. In this UI element, the
user is provided with a few suggestions of some values/texts. The value can
be chosen by the user while filling AutoCompleteTextView.

Android UI Layouts
Android Layout is used to define the user interface that holds the UI controls or
widgets that will appear on the screen of an android application or activity screen.
Generally, every application is a combination of View and ViewGroup. As we know,
an android application contains a large number of activities and we can say each
activity is one page of the application. So, each activity contains multiple user
interface components and those components are the instances of the View and
ViewGroup. All the elements in a layout are built using a hierarchy
of View and ViewGroup objects.

View

A View is defined as the user interface which is used to create interactive UI


components such as TextView, ImageView, EditText, RadioButton, etc., and is
responsible for event handling and drawing. They are Generally Called Widgets.

pg. 37
IMPORTANT NOTES
Mobile Application Development

View

A ViewGroup act as a base class for layouts and layouts parameters that hold other
Views or ViewGroups and to define the layout properties. They are Generally Called
layouts.

ViewGroup

The Android framework will allow us to use UI elements or widgets in two ways:
 Use UI elements in the XML file
 Create elements in the Kotlin file dynamically

Types of Android Layout

 Android Linear Layout: LinearLayout is a ViewGroup subclass, used to


provide child View elements one by one either in a particular direction
either horizontally or vertically based on the orientation property.

pg. 38
IMPORTANT NOTES
Mobile Application Development

 Android Relative Layout: RelativeLayout is a ViewGroup subclass, used


to specify the position of child View elements relative to each other like (A
to the right of B) or relative to the parent (fix to the top of the parent).
 Android Constraint Layout: ConstraintLayout is a ViewGroup subclass,
used to specify the position of layout constraints for every child View
relative to other views present. A ConstraintLayout is similar to a
RelativeLayout, but having more power.
 Android Frame Layout: FrameLayout is a ViewGroup subclass, used to
specify the position of View elements it contains on the top of each other to
display only a single View inside the FrameLayout.
 Android Table Layout: TableLayout is a ViewGroup subclass, used to
display the child View elements in rows and columns.
 Android Web View: WebView is a browser that is used to display the web
pages in our activity layout.
 Android ListView: ListView is a ViewGroup, used to display scrollable
lists of items in a single column.
 Android Grid View: GridView is a ViewGroup that is used to display a
scrollable list of items in a grid view of rows and columns.

Different Attribute of the Layouts

XML attributes Description

android:id Used to specify the id of the view.

Used to declare the width of View and ViewGroup


android:layout_width elements in the layout.

Used to declare the height of View and ViewGroup


android:layout_height elements in the layout.

Used to declare the extra space used on the left side


android:layout_marginLeft of View and ViewGroup elements.

Used to declare the extra space used on the right


android:layout_marginRight side of View and ViewGroup elements.

android:layout_marginTop Used to declare the extra space used in the top side

pg. 39
IMPORTANT NOTES
Mobile Application Development

XML attributes Description

of View and ViewGroup elements.

Used to declare the extra space used in the bottom


android:layout_marginBottom side of View and ViewGroup elements.

Used to define how child Views are positioned in


android:layout_gravity the layout.

Android Option Menu Example


Android Option Menus are the primary menus of android. They can be used for
settings, search, delete item etc.

Here, we are going to see two examples of option menus. First, the simple option
menus and second, options menus with images.

Here, we are inflating the menu by calling the inflate() method


of MenuInflater class. To perform event handling on menu items, you need to
override onOptionsItemSelected() method of Activity class.

Android Context Menu Example


Android context menu appears when user press long click on the element. It is also
known as floating menu.

It affects the selected content while doing action on it.

It doesn't support item shortcuts and icons.

Android Popup Menu Example


Android Popup Menu displays the menu below the anchor text if space is available
otherwise above the anchor text. It disappears if you click outside the popup menu.

pg. 40
IMPORTANT NOTES
Mobile Application Development

The android.widget.PopupMenu is the direct subclass of java.lang.Object class.

Android Toast Example

Andorid Toast can be used to display information for the short period of time. A
toast contains message to be displayed quickly and disappears after sometime.

The android.widget.Toast class is the subclass of java.lang.Object class.

You can also create custom toast as well for example toast displaying image. You can
visit next page to see the code for custom toast.

Toast class
Toast class is used to show notification for a particular interval of time. After
sometime it disappears. It doesn't block the user interaction.

Constants of Toast class

There are only 2 constants of Toast class which are given below.

Constant Description

public static final int LENGTH_LONG displays view for the long duration of time.

public static final int LENGTH_SHORT displays view for the short duration of time.

Methods of Toast class

The widely used methods of Toast class are given below.

Method Description

pg. 41
IMPORTANT NOTES
Mobile Application Development

public static Toast makeText(Context context, CharSequence makes the toast containing text and
text, int duration) duration.

public void show() displays toast.

public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.

Android Custom Toast Example


You are able to create custom toast in android. So, you can display some images like
congratulations or loss on the toast. It means you are able to customize the toast
now.

Android AlertDialog Example

Android AlertDialog can be used to display the dialog message with OK and Cancel
buttons. It can be used to interrupt and ask the user about his/her choice to continue
or discontinue.

Android AlertDialog is composed of three regions: title, content area and action
buttons.

Android AlertDialog is the subclass of Dialog class.

Methods of AlertDialog class


Method Description

public AlertDialog.Builder setTitle(CharSequence) This method is used to set the title of AlertDialog.

pg. 42
IMPORTANT NOTES
Mobile Application Development

public AlertDialog.Builder This method is used to set the message for


setMessage(CharSequence) AlertDialog.

public AlertDialog.Builder setIcon(int) This method is used to set the icon over
AlertDialog.

Android Service

pg. 43
IMPORTANT NOTES
Mobile Application Development

Android service is a component that is used to perform operations on the


background such as playing music, handle network transactions, interacting content
providers etc. It doesn't has any UI (user interface).

The service runs in the background indefinitely even if application is destroyed.

Moreover, service can be bounded by a component to perform interactivity and inter


process communication (IPC).

The android.app.Service is subclass of ContextWrapper class.

Play Video

Note: Android service is not a thread or separate process.

Life Cycle of Android Service


There can be two forms of a service.The lifecycle of service can follow two different
paths: started or bound.

1. Started
2. Bound

1) Started Service

A service is started when component (like activity) calls startService() method, now it
runs in the background indefinitely. It is stopped by stopService() method. The
service can stop itself by calling the stopSelf() method.

2) Bound Service

A service is bound when another component (e.g. client) calls bindService() method.
The client can unbind the service by calling the unbindService() method.

The service cannot be stopped until all clients unbind the service.

pg. 44
IMPORTANT NOTES
Mobile Application Development

Understanding Started and Bound Service by background


music example

Suppose, I want to play music in the background, so call startService() method. But I
want to get information of the current song being played, I will bind the service that
provides information about the current song.

Android Service Example


Let's see the example of service in android that plays an audio in the background.
Audio will not be stopped even if you switch to another activity. To stop the audio,
you need to stop the service.

pg. 45
IMPORTANT NOTES
Mobile Application Development

Android SQLite
SQLite is an open-source relational database i.e. used to perform database
operations on android devices such as storing, manipulating or retrieving persistent
data from the database.

It is embedded in android bydefault. So, there is no need to perform any database


setup or administration task.

Here, we are going to see the example of sqlite to store and fetch the data. Data is
displayed in the logcat. For displaying data on the spinner or listview, move to the
next page.

pg. 46
IMPORTANT NOTES
Mobile Application Development

SQLiteOpenHelper class provides the functionality to use the SQLite database.

SQLiteOpenHelper class
The android.database.sqlite.SQLiteOpenHelper class is used for database creation
and version management. For performing any database operation, you have to
provide the implementation of onCreate() and onUpgrade() methods of
SQLiteOpenHelper class.

Constructors of SQLiteOpenHelper class

There are two constructors of SQLiteOpenHelper class.

Constructor Description

SQLiteOpenHelper(Context context, String name, creates an object for creating,


SQLiteDatabase.CursorFactory factory, int version) opening and managing the database.

SQLiteOpenHelper(Context context, String name, creates an object for creating,


SQLiteDatabase.CursorFactory factory, int version, opening and managing the database.
DatabaseErrorHandler errorHandler) It specifies the error handler.

Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:

Method Description

public abstract void onCreate(SQLiteDatabase db) called only once when database is
created for the first time.

public abstract void onUpgrade(SQLiteDatabase db, int called when database needs to be
oldVersion, int newVersion) upgraded.

public synchronized void close () closes the database object.

pg. 47
IMPORTANT NOTES
Mobile Application Development

public void onDowngrade(SQLiteDatabase db, int called when database needs to be


oldVersion, int newVersion) downgraded.

SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update,
delete, select etc.

Methods of SQLiteDatabase class

There are many methods in SQLiteDatabase class. Some of them are as follows:

Method Description

void execSQL(String sql) executes the sql query not select query.

long insert(String table, String inserts a record on the database. The table specifies the
nullColumnHack, ContentValues table name, nullColumnHack doesn't allow completely null
values) values. If second argument is null, android will store null
values if values are empty. The third argument specifies the
values to be stored.

int update(String table, ContentValues updates a row.


values, String whereClause, String[]
whereArgs)

Cursor query(String table, String[] returns a cursor over the resultset.


columns, String selection, String[]
selectionArgs, String groupBy, String
having, String orderBy)

SQLiteDatabase
In Android, the SQLiteDatabase namespace defines the functionality to connect
and manage a database. It provides functionality to create, delete, manage and
display database content.

pg. 48
IMPORTANT NOTES
Mobile Application Development

Create a Database

Simple steps to create a database and handle are as follows.


1. Create "SQLiteDatabase" object.
2. Open or Create a database and create a connection.
3. Perform insert, update or delete operation.
4. Create a Cursor to display data from the table of the database.
5. Close the database connectivity.
Following tutorial helps you to create a database and insert records in it.

Step 1: Instantiate "SQLiteDatabase" object


1. SQLiteDatabase db;

Before you can use the above object, you must import
the android.database.sqlite.SQLiteDatabase namespace in your application.
1. db=openOrCreateDatabase(String path, int mode, SQLiteDatab
ase.CursorFactory factory)

This method is used to create/open database. As the name suggests, it will open
a database connection if it is already there, otherwise, it will create a new one.

Example,
1. db=openOrCreateDatabase("XYZ_Database",SQLiteDatabase.CREA
TE_IF_NECESSARY,null);

Arguments:

String path Name of the database


operating mode. Use 0 or "MODE_PRIVATE" for the default
Int mode operation, or "CREATE_IF_NECESSARY" if you like to give an
option that "if a database is not there, create it"
CursorFactory An optional factory class that is called to instantiate a cursor
factory when a query is called

Step 2: Execute DDL command


1. db.execSQL(String sql) throws SQLException

This command is used to execute a single SQL statement that doesn't return any
data means other than SELECT or any other.
1. db.execSQL("Create Table Temp (id Integer, name Text)");

pg. 49
IMPORTANT NOTES
Mobile Application Development

In the above example, it takes "CREATE TABLE" statement of SQL. This will create
a table of "Integer" & "Text" fields.

Try and Catch block is required while performing this operation. An exception
that indicates there was an error with SQL parsing or execution.

Step 3: Create an object of "ContentValues" and Initiate it.


1. ContentValues values=new ContentValues();

This class is used to store a set of values. We can also say, it will map
ColumnName and relevant ColumnValue.
1. values.put("id", eid.getText().toString());
2. values.put("name", ename.getText().toString());

String Key Name of the field as in table. Ex. "id", "name"


String Value Value to be inserted.

Step 4: Perform Insert Statement.


1. insert(String table, String nullColumnHack, ContentValues
values)

String table Name of table related to the database.


If not set to null, the nullColumnHack parameter provides the
String
name of nullable column name to explicitly insert a NULL into
nullColumnHack
in the case where your values is empty.
ContentValues
This map contains the initial column values for the row.
values

This method returns a long. The row ID of the newly inserted row, or -1 if an
error occurred.

Example,
1. db.insert("temp", null, values);

Step 5: Create Cursor

This interface provides random read-write access to the result set returned by a
database query.
1. Cursor c=db.rawQuery(String sql, String[] selectionArgs)

Strign sql The SQL query


String You may include ?s in where clause in the query, which will be

pg. 50
IMPORTANT NOTES
Mobile Application Development

replaced by the values from selectionArgs. The values will be


[]selectionArgs
bound as Strings.

Example,
1. Cursor c=db.rawQuery("SELECT * FROM temp",null);

Methods

moveToFirst Moves cursor pointer at a first position of a result set


moveToNextMoves cursor pointer next to the current position.
Returns false, if the cursor pointer is not atlast position of a result
isAfterLast
set.

Example,
1. c.moveToFirst();
2. while(!c.isAfterLast())
3. {
4. //statement…
5. c.moveToNext();
6. }
Step 6: Close Cursor and Close Database connectivity

It is very important to release our connections before closing our activity. It is


advisable to release the Database connectivity in "onStop" method. And Cursor
connectivity after use it.

pg. 51

You might also like