Unit-4
Unit-4
• It is embedded in android by default. So, there is no need to perform any database setup or administration task.
In order to access this database, you don’t need to establish any kind of connections for it like JDBC,ODBC,
etc.
• SQLite databases are particularly useful for storing data locally on the device, caching data, and working
with structured datasets in Android applications.
– Local Data Storage: SQLite databases are used in Android to store structured data on the device itself.
This is particularly useful for scenarios where you need to store data that is specific to the app and
doesn’t need to be shared with other applications or synced with a remote server.
– Relational Database: SQLite is a relational database management system, which means it supports
tables with rows and columns and the ability to define relationships between tables. This makes it
suitable for managing structured data.
– CRUD Operations: SQLite supports standard database operations, often referred to as CRUD (Create,
Read, Update, Delete) operations. You can create tables, insert data, query data, update data, and delete
data in the database.
– Content Providers: In Android, SQLite databases are commonly used with content providers, which
allow data to be shared between different applications. Content providers provide a standard interface
to access data stored in the SQLite database.
– OpenHelper Class: To work with SQLite databases in Android, developers create a subclass of the
SQLiteOpenHelper class. This class helps in managing database creation and version management.
– SQL Queries: To interact with the database, developers use SQL (Structured Query Language) queries.
These queries allow you to create, update, and retrieve data from the database.
– Security: SQLite databases on Android are secure and private to the application that creates them.
They are stored in the app’s private directory and can’t be accessed by other applications unless you
explicitly share data through content providers or other mechanisms.
– Performance: SQLite is known for its performance, especially when dealing with structured data. It’s
highly optimized and can efficiently handle database operations, even on resource-constrained mobile
devices.
102
4.1.1 How Data is Being Stored in the SQLite Database?
• Data is stored in the SQLite database in the form of tables.
• When we stored this data in our SQLite database it is arranged in the form of tables that are similar to that of
an excel sheet.
• Below is the representation of our SQLite database which we are storing in our SQLite database.
103
4.1.2 SQLite architecture
• SQLite is, as previously mentioned, written in the C programming language while Android applications are
primarily developed using Java. To bridge this “language gap”, the Android SDK includes a set of classes
that provide a Java layer on top of the SQLite database management system. The remainder of this chapter
will provide a basic overview of each of the major classes within this category.
• There are many libraries and classes available on Android to perform any kind of database queue on SQLite.
It provides so many commands like add new data, update, read, and delete data.
104
4.1.3 Android SQLite Classes
4.1.3.1 SQLiteOpenHelper Class
• Android has features available to handle changing database schemas, which mostly depend on using the
SQLiteOpenHelper class. SQLiteOpenHelper is designed to get rid of two very common problems.
– When the application runs the first time - At this point, we do not yet have a database. So we will have
to create the tables, indexes, starter data, and so on.
– When the application is upgraded to a newer schema - Our database will still be on the old schema from
the older edition of the app. We will have option to alter the database schema to match the needs of the
rest of the app.
• For creating, updating and other operations you need to create a subclass or SQLiteOpenHelper class.
SQLiteOpenHelper is a helper class to manage database creation and version management.
• The SQLiteOpenHelper is responsible for opening database if exist, creating database if it does not exists
and upgrading if required.
• The SQLiteOpenHelper only require the DATABASE_NAME to create database. After extending SQLi-
teOpenHelper you will need to implement its methods onCreate, onUpgrade and constructor.
• This class provides two methods onCreate(SQLiteDatabase db), onUpgrade(SQLiteDatabase db, int old-
Version, int newVersion).
• onCreate(SQLiteDatabase sqLiteDatabase) method is called only once throughout the application life-
cycle. It will be called whenever there is a first call to getReadableDatabase() or getWritableDatabase()
function available in super SQLiteOpenHelper class. So SQLiteOpenHelper class call the onCreate() method
after creating database and instantiate SQLiteDatabase object. Database name is passed in constructor call.
• onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) is only called whenever there is a upda-
tion in existing version. So to update a version we have to increment the value of version variable passed in
the superclass constructor.
105
106
4.1.3.2 SQLiteDatabase Class
• The SQLiteDatabase class in Android is a fundamental part of working with SQLite databases. It provides
methods and functionality for managing and interacting with an SQLite database.
• SQLiteDatabase provides methods for various database operations, including creating tables, inserting,
updating, deleting, and querying data. Some key methods of this classare as follows:
• You should open the database using the getReadableDatabase() or getWritableDatabase() methods pro-
vided by your database helper. It’s essential to close the database when you’re done with it to release system
resources. You can use the close() method for this purpose.
107
• In this example, we create or open a database, insert data, and query data from a table using the SQLite-
Database class.
108
4.1.3.3 Cursor Class
• The Cursor class in Android is an integral part of working with SQLite databases.
• A class provided specifically to provide access to the results of a database query. It provides a way to retrieve
and manipulate data from a database, especially when you want to query data from tables.
• A Cursor is used to represent the result set of a database query. It allows you to navigate through the rows
and columns of the data retrieved from a database table.
• You use a Cursor object to execute SQL queries that return data, like SELECT statements. The result of the
query is stored in the Cursor, and you can move through the results row by row.
• For example, a SQL SELECT operation performed on a database will potentially return multiple matching
rows from the database. A Cursor instance can be used to step through these results, which may then be
accessed from within the application code using a variety of methods.
• Some key methods of this class are as follows:
109
• In this example, we execute a query to retrieve "name" and "age" columns from a table. We use the Cursor to
move through the result set and retrieve data from each row.
110
4.2 Sensors
• Most Android-powered devices have built-in sensors that measure motion, orientation, and various environ-
mental conditions.
• Sensors are physical components built into a handset or tablet device. They derive their data by directly
measuring specific environmental properties, such as acceleration, geomagnetic field strength, or angular
change.
• These sensors are capable of providing raw data with high precision and accuracy, and are useful if you
want to monitor three-dimensional device movement or positioning, or you want to monitor changes in the
ambient environment near a device.
• For example, a game might track readings from a device’s gravity sensor to infer complex user gestures and
motions, such as tilt, shake, rotation, or swing.
• Likewise, a weather application might use a device’s temperature sensor and humidity sensor to calculate
and report the dewpoint, or a travel application might use the geomagnetic field sensor and accelerometer to
report a compass bearing.
• The Android platform supports three broad categories of sensors:
– Motion sensors: These sensors measure acceleration forces and rotational forces along three axes.
This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
– Environmental sensors: These sensors measure various environmental parameters, such as ambient air
temperature and pressure, illumination, and humidity. This category includes barometers, photometers,
and thermometers.
– Position sensors: These sensors measure the physical position of a device. This category includes
orientation sensors and magnetometers.
111
112
4.2.1 Sensor Framework
You can access these sensors and acquire raw sensor data by using the Android sensor framework. The sensor
framework is part of the android.hardware package and includes the following classes and interfaces:
4.2.1.1 SensorManager
You can use this class to create an instance of the sensor service. This class provides various methods for accessing
and listing sensors, registering and unregistering sensor event listeners, and acquiring orientation information. This
class also provides several sensor constants that are used to report sensor accuracy, set data acquisition rates, and
calibrate sensors.
4.2.1.2 Sensor
You can use this class to create an instance of a specific sensor. This class provides various methods that let you
determine a sensor’s capabilities.
4.2.1.3 SensorEvent
The system uses this class to create a sensor event object, which provides information about a sensor event. A
sensor event object includes the following information: the raw sensor data, the type of sensor that generated the
event, the accuracy of the data, and the timestamp for the event.
4.2.1.4 SensorEventListener
You can use this interface to create two callback methods that receive notifications (sensor events) when sensor
values change or when sensor accuracy changes.
113
4.3 Bluetooth
• Bluetooth is a wireless communication technology that enables data exchange over short distances between
Android devices.
• In Android, Bluetooth is implemented through the Android Bluetooth API, which allows developers to
create applications that can discover, pair with, and communicate with other Bluetooth devices, such as
smartphones, tablets, headphones, speakers, and more.
• Bluetooth Stack: Android devices use the Bluetooth stack to enable Bluetooth communication. Android
supports multiple Bluetooth profiles for various use cases, including A2DP (audio streaming), SPP (serial
port profile), and many others.
• Bluetooth Permissions: To use Bluetooth in your Android app, you need to declare the necessary permis-
sions in your AndroidManifest.xml file, such as BLUETOOTH, BLUETOOTH_ADMIN, and BLUE-
TOOTH_CONNECT for basic Bluetooth operations.
• Enabling Bluetooth: You can programmatically enable or disable Bluetooth on the device using the
BluetoothAdapter class. Users will also be prompted for consent when enabling Bluetooth via your app.
• Device Discovery: The Android Bluetooth API allows you to discover nearby Bluetooth devices. You can
search for nearby devices and retrieve a list of available devices, including their names and addresses.
• Pairing and Bonding: Pairing is the process of establishing a connection between two Bluetooth devices.
Bonding is an optional, more secure process that involves saving the pairing information for future connec-
tions. Android handles pairing and bonding processes automatically when connecting to devices.
• Device Connections: You can connect to a remote Bluetooth device using its MAC address and the
BluetoothSocket class. Once a connection is established, you can send and receive data over the Bluetooth
channel.
• Bluetooth Profiles: Android supports various Bluetooth profiles, which define how different types of devices
can communicate with one another. Examples include:
– A2DP (Advanced Audio Distribution Profile): For streaming audio to headphones or speakers.
– HFP (Hands-Free Profile): For Bluetooth headsets and car kits.
– SPP (Serial Port Profile): For serial communication, often used for IoT devices.
– GATT (Generic Attribute Profile): For low-energy Bluetooth communication, used by Bluetooth Low
Energy (BLE) devices.
• Bluetooth Low Energy (BLE): Android also supports Bluetooth Low Energy (BLE), which is a power-
efficient version of Bluetooth primarily used for IoT devices, beacons, and wearable technology. The Android
BLE API allows your app to communicate with BLE devices.
• Bluetooth Permissions and Security: Bluetooth communications should be secure. Android provides the
means to secure Bluetooth communications, including encryption and authentication. Be aware of security
best practices when using Bluetooth in your app.
• Bluetooth in App Development: You can develop various types of applications using Bluetooth, such as:
– Bluetooth file transfer apps for sharing files between devices.
– Bluetooth chat applications for text messaging.
– Bluetooth control apps for remotely controlling other devices.
– Bluetooth-based IoT applications for controlling smart devices.
– Bluetooth audio streaming applications for wireless music playback.
• Compatibility and Version: Different Android devices may have different Bluetooth versions and capabili-
ties. Ensure that your app accounts for variations in Bluetooth support.
114
4.3.1 BluetoothAdapter class
• The BluetoothAdapter class in Android is a key component of the Android Bluetooth API. It represents the
device’s own Bluetooth adapter and provides methods for various Bluetooth-related operations.
• This class allows you to control the device’s Bluetooth functionality, including enabling or disabling Bluetooth,
discovering nearby devices, and establishing connections.
115
4.4 Geo Location - Location Based Services
• You must have used apps like Google Maps, Waze, MapQuest, etc. These are the applications that help you
track the location of the device. They also provide services like finding nearby restaurants, hospitals, petrol
pumps, etc. Even the cab drivers now use maps to locate their route.
• Location-based services (LBS) in Android app development involve using the device’s location (latitude and
longitude coordinates) to provide users with location-specific information, features, or services.
• These services leverage various technologies, including GPS (Global Positioning System), network-based
positioning, and sensors, to determine a device’s geographic location accurately. Location-based services are
widely used in applications such as maps and navigation, social networking, weather forecasting, geotagging,
location-based advertising, and more.
• Location-Based Services(LBS) are present in Android to provide you with features like current location
detection, display of nearby places, geofencing, etc. It fetches the location using your device’s GPS, Wifi, or
Cellular Networks.
• To build an app with location-based services, you need to access the Google Play Services Module. After that,
you need to use a framework called Location Framework, which has many methods, classes, and interfaces
to make your task easier.
• Location Providers: Android provides two primary location providers to determine a device’s location:
– GPS Provider: This provider uses signals from multiple satellites to calculate the device’s precise
location. It’s accurate but may require an unobstructed view of the sky.
– Network Provider: This provider uses cell tower and Wi-Fi signals to estimate the device’s location.
It works indoors and is quicker to provide a location fix but is less accurate than GPS.
• To access the device’s location, your app needs the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
permission, depending on the desired level of accuracy. You must request these permissions in your app’s
manifest file and handle them at runtime on Android 6.0 (API level 23) and later.
• float distanceTo(Location destination): It gives the approximate distance between our current location and
the destination location.
116
• float getSpeed(): It gives the speed of our location change.
• void setAccuracy(float accuracy): Using setAccuracy(), you can set your custom accuracy in metres.
• void setAltitude(double altitude): Using setAltitude(), you can set the altitude of your place from sea level
in metres.
• void setBearing(float bearing): Using the setBearing() method, you can set location bearing in degrees.
• void setLongitude(double longitude): You can even set your location to some other longitude using the
setLongitude() method.
• void setSpeed(float speed): You can even set speed using the setSpeed() method.
• void reset(): It is used to reset your set location.
• boolean hasAccuracy(): It says whether or not the location is accurate.
• boolean hasAltitude(): It says if the place has an altitude or not
117
4.5 SMS and MMS
• We always send messages to others. In older days people have only one means of communication i.e, letters
but nowadays there are many ways to send messages like email, SMS, MMS, and messages on the OTT
(over-the-top) application like WhatsApp, telegram, and signal.
• The two main ways to send messages on the mobile phone using a cellular network are MMS and SMS. All
the mobile operating systems support the MMS and SMS through their default messaging application.
• We need not download some additional applications for sending them. All devices do not support MMS it
completely depends on the operator that is providing us the cellular network.
• Both the SMS and MMS fall into the same category of Text Messaging but there are a lot of differences
between them.
• SMS stands for Short Messaging Service.
– It was invented in 1980. It is the oldest and most widely used form of text messaging on mobile devices.
– This form of messaging is fully operational and it is supported by all the mobile devices, and we need
not download some other application to use it. We do not need to have a smartphone to use it.
– There are some problems with the SMS like it allows message length up to 160 characters. If the length
was above it then the message will be split into multiple messages.
– Another problem with SMS is that it does not support multimedia.
• MMS stands for Multimedia Messaging Service.
– MMS is just an extension of the features of the SMS. It is also sent over cellular networks.
– The MMS is more appealing in comparison to SMS because of the images and videos we can use in
them. It allows users to send Multimedia like images, GIF, videos with text which was not supported in
the SMS.
– The maximum length supported by it depends on the cellular operator not generally speaking it is 10
times more than SMS. The typical length is 1600.
– It is not supported by every mobile device. It is more suitable for smartphones and not for analog
cellphones. Sending MMS is more costly in comparison to sending SMS.
118
119
4.5.1 SMSManager
• Android provides full SMS functionality from within your applications through the SMSManager.
• SMSManager class manages operations like sending a text message, data message, and multimedia messages
(MMS). For sending a text message method sendTextMessage() is used likewise for multimedia message
sendMultimediaMessage() and for data message sendDataMessage() method is used.
120
4.6 Graphics and Animation
• Animation is the process of adding a motion effect to any view, image, or text. With the help of an animation,
you can add motion or can change the shape of a specific view.
• Android provides a variety of powerful APIs for applying animation to UI elements and drawing custom 2D
and 3D graphics.
• Animation are generally used to give your application UI a rich look and feel. Animation in android apps is
the process of creating motion and shape change. The basic ways of animation are:
– Fade In Animation
– Fade Out Animation
– Cross Fading Animation
– Blink Animation
– Zoom In Animation
– Zoom Out Animation
– Rotate Animation
– Move Animation
– Slide Up Animation
– Slide Down Animation
– Bounce Animation
– Sequential Animation
– Together Animation
• The Android framework provides two animation systems: property animation (introduced in Android
3.0) and view animation. Both animation systems are viable options, but the property animation system, in
general, is the preferred method to use, because it is more flexible and offers more features. In addition to
these two systems, you can utilize Drawable animation, which allows you to load drawable resources and
display them one frame after another.
121
122
4.7 Sample Questions
Marks Sample Question
2 Does Android employ SQLite as a relational database management system? If affirmative, could you
provide an illustrative example?
2 Is a cursor utilized for the management of query results in Android databases? In case of affirmation,
kindly provide an example.
2 Can helper classes be utilized to initiate and conclude the operations of an Android database? If so,
kindly furnish an example.
4 Please elucidate the purpose and function of the component designated for the storage and retrieval
of extensive or structured data sets shared among Android applications. How does this component
facilitate the exchange of data?
4 Describe the specific permission necessary to access the Bluetooth functionality on Android devices.
Expound on its significance and potential use scenarios for Bluetooth-related tasks.
6 Examine the involvement of sensors in Android devices and furnish examples of applications that
harness various types of sensors.
6 Delve into the benefits and hurdles associated with the integration of Bluetooth technology in the
development of Android applications.
6 Contrast and equate GPS-based and network-based location services in the Android ecosystem.
3 Define the concept of "Geo Location" within the Android context and elaborate on the methodology
for ascertaining a device’s location through GPS or other location techniques.
3 Clarify the abbreviations "SMS" and "MMS" as they pertain to Android. Disclose the full meanings
of these terms and outline their distinctions.
3 Android provides a comprehensive framework for 2D drawing. Examine the pivotal classes involved,
such as Canvas, Paint, and others, and their contributions to the drawing process.
4 Describe the realm of graphics and animation within Android app development.
4 Provide instances of scenarios in which you would employ Frame Animation and Tween Animation
in an Android application.
18 Formulate a conceptual design for an Android application aimed at assisting users in tracking their
daily water consumption. Include the primary interface and essential functionalities.
18 Craft a prototype for an Android application that harnesses sensors to monitor and enhance sleep
quality. Elaborate on the app’s capabilities and the integration of sensors.
123
4.8 Related Videos
• SQLite Database Tutorial - 1
https://www.youtube.com/watch?v=DVWGY-4Cc3Y
https://www.youtube.com/watch?v=C2uiPWyYWmY
https://www.youtube.com/watch?v=IQAXYZrOrMg
• SQLite Database Tutorial - 2
https://www.youtube.com/watch?v=Ip0LaPUcxiU
https://www.youtube.com/watch?v=HQo4Nr2d3DA
https://www.youtube.com/watch?v=7NJavvSLYx8
https://www.youtube.com/watch?v=SoqujjHpO8Q
https://www.youtube.com/watch?v=rK4walNCMzI
https://www.youtube.com/watch?v=lqoVrGWFrJI
• Sensors
https://www.youtube.com/watch?v=H0dxrwRT1aE
https://www.youtube.com/watch?v=gVszXHio7hU
https://www.youtube.com/watch?v=SvOKrWf7cmc
https://www.youtube.com/watch?v=R-8k2GYK1G4
• Bluetooth
https://www.youtube.com/watch?v=KfM5N6m10kY
• Geo Location - Location Based Services
https://www.youtube.com/watch?v=BO1utHYhsms
https://www.youtube.com/watch?v=xg6r4AnPZzY
https://www.youtube.com/watch?v=InTLAZ99Y40
• SMS and MMS
https://www.youtube.com/watch?v=ksD2ItUkfLc
• Graphics and Animation
https://www.youtube.com/watch?v=LoluU2Jg0Es
https://www.youtube.com/watch?v=XHgqo-PgjGA
124