Unit4 MAD
Unit4 MAD
Content Providers are a very important component that serves the purpose of a
relational database to store the data of applications. The role of the content
provider in the android system is like a central repository in which data of the
applications are stored, and it facilitates other applications to securely access and
modifies that data based on the user requirements. Android system allows the
content provider to store the application data in several ways. Users can manage
to store the application data like images, audio, videos, and personal contact
information by storing them in SQLite Database, in files, or even on a network.
In order to share the data, content providers have certain permissions that are
used to grant or restrict the rights to other applications to interfere with the data.
Content URI
Content URI(Uniform Resource Identifier) is the key concept of Content
providers. To access the data from a content provider, URI is used as a query
string.
Structure of a Content URI: content://authority/optionalPath/optionalID
Details of different parts of Content URI:
content:// – Mandatory part of the URI as it represents that the given URI is a
Content URI.
authority – Signifies the name of the content provider like contacts, browser,
etc. This part must be unique for every content provider.
optionalPath – Specifies the type of data provided by the content provider. It
is essential as this part helps content providers to support different types of
data that are not related to each other like audio and video files.
optionalID – It is a numeric value that is used when there is a need to access a
particular record.
If an ID is mentioned in a URI then it is an id-based URI otherwise a
directory-based URI.
Operations in Content Provider
Four fundamental operations are possible in Content Provider
namely Create, Read, Update, and Delete. These operations are often termed
as CRUD operations.
Create: Operation to create data in a content provider.
Read: Used to fetch data from a content provider.
Update: To modify existing data.
Delete: To remove existing data from the storage.
Working of the Content Provider
UI components of android applications like Activity and Fragments use an
object CursorLoader to send query requests to ContentResolver. The
ContentResolver object sends requests (like create, read, update, and delete) to
the ContentProvider as a client. After receiving a request, ContentProvider
process it and returns the desired result. Below is a diagram to represent these
processes in pictorial form.
Following are the six abstract methods and their description which are
essential to override as the part of ContenProvider class:
Abstract
Method Description
A method that accepts arguments and fetches the data from the
query()
desired table. Data is retired as a cursor object.
SMS Messaging:
sending a text SMS over the phone using the SMSManager class in an Android
application. For this, a basic knowledge of the fundamentals of android app
development, creating a new project , running an android app , Views,
and handling of click event buttons is required.
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. The details of each function are:
Function Description
sendTextMessage(String destinationAddress,
String scAddress, String text, PendingIntent
sendTextMessage()
sentIntent,
PendingIntent deliveryIntent, long messageId)
sendDataMessage(String destinationAddress,
String scAddress, short destinationPort, byte[] data,
sendDataMessage()
PendingIntent sentIntent, PendingIntent
deliveryIntent)
sendMultimediaMessage(Context context,
sendMultimediaMessage(
Uri contentUri, String locationUrl,
)
Bundle configOverrides, PendingIntent sentIntent
Below is an example of a basic application that sends a text message.
Sending Email: To make a basic Android Application that can be used to send
email through your android application. You can do so with the help
of Intent with action as ACTION_SEND with extra fields:
email id to which you want to send mail,
the subject of the email and
body of the email.
Basically Intent is a simple message object that is used to communicate
between android components such as activities, content providers, broadcast
receivers, and services, here use to send the email. This application basically
contains one activity with EditText to take input of email address, subject, and
body of the email from the user and button to send that email.
Displaying Maps
Maps are of great use and it increases the productivity of an app. Google Maps
API allows Android developers to integrate Google Maps in their app. Below is
the step-by-step process to integrate Google Maps into Android applications:
1. Goto https://developers.google.com/maps/documentation/android-api/signup
and click on “GET STARTED” button as shown in the figure:
2. Now select the Map checkbox and click on the Continue button as shown
below:
3. Select a project in which you want to enable Google Map API, and click on
Next. A new key will be generated for the chosen project.
1. Go to https://console.developers.google.com/apis/credentials
2. In the API keys section, click on Pencil button made on the right of API key
that you want to select, for attaching your app with.
Using the Google Play services location APIs, your app can request the last known
location of the user's device. In most cases, you are interested in the user's current
location, which is usually equivalent to the last known location of the device.
Specifically, use the fused location provider to retrieve the device's last known
location. The fused location provider is one of the location APIs in Google Play
services. It manages the underlying location technology and provides a simple API
so that you can specify requirements at a high level, like high accuracy or low
power. It also optimizes the device's use of battery power.
Set up Google Play services
To access the fused location provider, your app's development project must include
Google Play services. Download and install the Google Play services component
via the SDK Manager and add the library to your project.
Specify app permissions
Apps whose features use location services must request location permissions,
depending on the use cases of those features.
Create location services client
Once you have created the Location Services client you can get the last known
location of a user's device. When your app is connected to these you can use the
fused location provider's getLastLocation() method to retrieve the device location.
The precision of the location returned by this call is determined by the permission
setting you put in your app manifest. To request the last known location, call
the getLastLocation() method.
The getLastLocation() method returns a Task that you can use to get
a Location object with the latitude and longitude coordinates of a geographic
location. The location object may be null in the following situations:
Location is turned off in the device settings. The result could be null even if the
last location was previously retrieved because disabling location also clears the
cache.
The device never recorded its location, which could be the case of a new device or
a device that has been restored to factory settings.
Google Play services on the device has restarted, and there is no active Fused
Location Provider client that has requested location after the services restarted. To
avoid this situation you can create a new client and request location updates
yourself.
Monitoring a location:
Here are some ways to monitor a location on an Android device:
Turn on location services
Open Settings, tap Security & Location, then Location, and toggle Location to on.
Select a location mode
Open Settings, tap Security & Location, then Location, then Mode, and choose a
mode. For example, High accuracy uses GPS, Wi-Fi, mobile networks, and
sensors for the most accurate location.
Create a geofence
Learn how to request location permissions and create and monitor geofences.
Use a foreground service
Use a foreground service to track a user's location in the background while
showing a notification that the app is active. This method has fewer restrictions
than using a background service, but you might need additional permissions.
Use a client to request location updates
If location is turned off in the device settings, or if Google Play services have
restarted, you can create a new client and request location updates yourself.
Introduction to SQLite:
SQLite engine is not a standalone process like other databases, you can link it
statically or dynamically as per your requirement with your application. SQLite
accesses its storage files directly.
Importance of SQLite:
SQLite does not require a separate server process or system to operate
(serverless).
SQLite comes with zero-configuration, which means no setup or
administration needed.
A complete SQLite database is stored in a single cross-platform disk file.
SQLite is very small and light weight, less than 400KiB fully configured or
less than 250KiB with optional features omitted.
SQLite is self-contained, which means no external dependencies.
SQLite transactions are fully ACID-compliant, allowing safe access from
multiple processes or threads.
SQLite supports most of the query language features found in SQL92
(SQL2) standard.
SQLite is written in ANSI-C and provides simple and easy-to-use API.
SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and
Windows (Win32, WinCE, WinRT).
SQLite Commands
The standard SQLite commands to interact with relational databases are similar to
SQL. They are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP.
These commands can be classified into groups based on their operational nature −
DDL - Data Definition Language
Sr.No
Command & Description
.
CREATE
1 Creates a new table, a view of a table, or other object
in database.
2 ALTER
Modifies an existing database object, such as a table.
DROP
3 Deletes an entire table, a view of a table or other
object in the database.
INSER
1 T
Creates
a record
UPDAT
2 E
Modifies
records
DELET
3 E
Deletes
records
1 SELECT
Retrieves certain records from one or more tables
SQLite - Installation
SQLite is famous for its great feature zero-configuration, which means no complex
setup or administration is needed.
Install SQLite on Windows
Step 1 − Go to SQLite download page, and download precompiled binaries
from Windows section.
Step 2 − Download sqlite-shell-win32-*.zip and sqlite-dll-win32-*.zip
zipped files.
Step 3 − Create a folder C:\>sqlite and unzip above two zipped files in this
folder, which will give you sqlite3.def, sqlite3.dll and sqlite3.exe files.
Step 4 − Add C:\>sqlite in your PATH environment variable and finally go
to the command prompt and issue sqlite3 command, which should display
the following result.
SQLite - Commands
simple and useful commands used by SQLite programmers. These commands are
called SQLite dot commands and exception with these commands is that they
should not be terminated by a semi-colon (;).
start with typing a simple sqlite3 command at command prompt which will
provide you with SQLite command prompt where you will issue various SQLite
commands.
$sqlite3
SQLite version 3.3.6
Enter ".help" for instructions
sqlite>
For a listing of the available dot commands, you can enter ".help" any time. For
example −
sqlite>.help
The above command will display a list of various important SQLite dot commands,
which are listed in the following table.
SQLite Statements
All the SQLite statements start with any of the keywords like SELECT, INSERT,
UPDATE, DELETE, ALTER, DROP, etc., and all the statements end with a
semicolon (;).
ANALYZE;
or
ANALYZE database_name;
or
ANALYZE database_name.table_name;
BEGIN;
or
BEGIN EXCLUSIVE TRANSACTION;
COMMIT;
COMMIT;
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
SQLite IN Clause
PRAGMA pragma_name;
For example:
PRAGMA page_size;
PRAGMA cache_size = 1024;
PRAGMA table_info(table_name);
RELEASE savepoint_name;
ROLLBACK;
or
ROLLBACK TO SAVEPOINT savepoint_name;
SAVEPOINT savepoint_name;
UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];
VACUUM;
SQLite - Data Type: SQLite data type is an attribute that specifies the type of data
of any object. Each column, variable and expression has related data type in
SQLite.
You would use these data types while creating your tables. SQLite uses a more
general dynamic type system. In SQLite, the datatype of a value is associated with
the value itself, not with its container.
Each value stored in an SQLite database has one of the following storage classes −
Sr.No
Storage Class & Description
.
1 NULL
The value is a NULL value.
INTEGER
2 The value is a signed integer, stored in 1, 2, 3, 4, 6, or
8 bytes depending on the magnitude of the value.
REAL
3 The value is a floating point value, stored as an 8-byte
IEEE floating point number.
TEXT
4 The value is a text string, stored using the database
encoding (UTF-8, UTF-16BE or UTF-16LE)
BLOB
5 The value is a blob of data, stored exactly as it was
input.
SQLite storage class is slightly more general than a datatype. The INTEGER
storage class, for example, includes 6 different integer datatypes of different
lengths.
Following table lists down various data type names which can be used while
creating SQLite3 tables with the corresponding applied affinity.
INT
INTEGER
TINYINT
SMALLINT
MEDIUMINT INTEGER
BIGINT
UNSIGNED BIG INT
INT2
INT8
CHARACTER(20) TEXT
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB
BLOB NONE
no datatype specified
REAL
DOUBLE REAL
DOUBLE PRECISION
FLOAT
NUMERIC
DECIMAL(10,5)
BOOLEAN NUMERIC
DATE
DATETIME
Boolean Datatype
SQLite does not have a separate Boolean storage class. Instead, Boolean values are
stored as integers 0 (false) and 1 (true).
SQLite does not have a separate storage class for storing dates and/or times, but
SQLite is capable of storing dates and times as TEXT, REAL or INTEGER values.
Sr.No
Storage Class & Date Formate
.
TEXT
1 A date in a format like "YYYY-MM-DD
HH:MM:SS.SSS"
REAL
2 The number of days since noon in Greenwich on
November 24, 4714 B.C.
INTEGER
3 The number of seconds since 1970-01-01 00:00:00
UTC
You can choose to store dates and times in any of these formats and freely convert
between formats using the built-in date and time functions.
SQLite - CREATE Database
Syntax
$sqlite3 DatabaseName.db
Syntax
Here, 'Alias-Name' is the same alias, which you had used while attaching the
database using ATTACH statement.
SQLite - CREATE Table
SQLite CREATE TABLE statement is used to create a new table in any of the
given database. Creating a basic table involves naming the table and defining its
columns and each column's data type.
Syntax
CREATE TABLE : is the keyword telling the database system to create a new
table. The unique name or identifier for the table follows the CREATE TABLE
statement. Optionally, you can specify database_name along with table_name.
Syntax: Following is the basic syntax of DROP TABLE statement. You can
optionally specify the database name along with table name as follows −
DROP TABLE database_name.table_name;
SQLite INSERT INTO Statement is used to add new rows of data into a table in
the database.
Syntax
Following are the two basic syntaxes of INSERT INTO statement.
INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Here, column1, column2,...columnN are the names of the columns in the table into
which you want to insert data.
You may not need to specify the column(s) name in the SQLite query if you are
adding values for all the columns of the table. However, make sure the order of the
values is in the same order as the columns in the table. The SQLite INSERT INTO
syntax would be as follows −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
SQLite SELECT statement is used to fetch the data from a SQLite database table
which returns data in the form of a result table. These result tables are also
called result sets.
Syntax
Following is the basic syntax of SQLite SELECT statement.
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2 ... are the fields of a table, whose values you want to
fetch. If you want to fetch all the fields available in the field, then you can use the
following syntax −
SELECT * FROM table_name;
Operator in SQLite
An operator is a reserved word or a character used primarily in an SQLite
statement's WHERE clause to perform operation(s), such as comparisons and
arithmetic operations.Operators are used to specify conditions in an SQLite
statement and to serve as conjunctions for multiple conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Bitwise operators
SQLite Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then SQLite arithmetic
operators will be used as follows −
Show Examples
Operator Description Example
a + b
Adds values on either side of the
+ (Addition) will give
operator
30
Assume variable a holds 10 and variable b holds 20, then SQLite comparison
operators will be used as follows
Show Examples
Operator Example
Description
Show Examples
Sr.No
Operator & Description
.
AND
1 The AND operator allows the existence of multiple
conditions in an SQL statement's WHERE clause.
BETWEEN
2 The BETWEEN operator is used to search for values
that are within a set of values, given the minimum
value and the maximum value.
EXISTS
3 The EXISTS operator is used to search for the
presence of a row in a specified table that meets
certain criteria.
IN
4 The IN operator is used to compare a value to a list of
literal values that have been specified.
NOT IN
5 The negation of IN operator which is used to compare
a value to a list of literal values that have been
specified.
LIKE
6 The LIKE operator is used to compare a value to
similar values using wildcard operators.
GLOB
7 The GLOB operator is used to compare a value to
similar values using wildcard operators. Also, GLOB
is case sensitive, unlike LIKE.
NOT
The NOT operator reverses the meaning of the logical
8 operator with which it is used. Eg. NOT EXISTS,
NOT BETWEEN, NOT IN, etc. This is negate
operator.
OR
9 The OR operator is used to combine multiple
conditions in an SQL statement's WHERE clause.
IS NULL
10 The NULL operator is used to compare a value with a
NULL value.
11 IS
The IS operator work like =
12 IS NOT
The IS operator work like !=
13 ||
Adds two different strings and make new one.
UNIQUE
14 The UNIQUE operator searches every row of a
specified table for uniqueness (no duplicates).
SQLite – Expressions
These expressions are used to perform any mathematical operation in any query.
Following is the syntax −
SQL expressions are like formulas and they are written in query language. You can
also use to query the database for a specific set of data.
Syntax
SQLite Boolean Expressions fetch the data on the basis of matching single value.
Following is the syntax −
There are several built-in functions such as avg(), sum(), count(), etc., to perform
what is known as aggregate data calculations against a table or a specific table
column.
Date Expressions returns the current system date and time values. These
expressions are used in various data manipulations.
If the given condition is satisfied, means true, then it returns the specific value
from the table. You will have to use WHERE clause to filter the records and
fetching only necessary records.
The WHERE clause not only is used in SELECT statement, but it is also used in
UPDATE, DELETE statement, etc., which will be covered in subsequent chapters.
Syntax
Following is the basic syntax of SQLite SELECT statement with WHERE clause.
Syntax
Syntax
Example
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
SQLite DELETE Query is used to delete the existing records from a table. You
can use WHERE clause with DELETE query to delete the selected rows, otherwise
all the records would be deleted.
Syntax
The percent sign represents zero, one, or multiple numbers or characters. The
underscore represents a single number or character. These symbols can be used in
combinations.
Syntax
SQLite GLOB operator is used to match only text values against a pattern using
wildcards. If the search expression can be matched to the pattern expression, the
GLOB operator will return true, which is 1. Unlike LIKE operator, GLOB is case
sensitive and it follows syntax of UNIX for specifying THE following wildcards.
The asterisk sign (*)
The question mark (?)
The asterisk sign (*) represents zero or multiple numbers or characters. The
question mark (?) represents a single number or character.
Syntax
Following is the basic syntax of * and ?.
SELECT FROM table_name
WHERE column GLOB 'XXXX*'
or
SELECT FROM table_name
WHERE column GLOB '*XXXX*'
or
SELECT FROM table_name
WHERE column GLOB 'XXXX?'
or
SELECT FROM table_name
WHERE column GLOB '?XXXX'
or
SELECT FROM table_name
WHERE column GLOB '?XXXX?'
or
SELECT FROM table_name
WHERE column GLOB '????'
You can combine N number of conditions using AND or OR operators. Here,
XXXX could be any numeric or string value.
Example
Following table lists a number of examples showing WHERE part having different
GLOB clause with '*' and '?' operators.
Sr.No
Statement & Description
.
1 WHERE SALARY GLOB '200*'
Finds any values that start with 200
SQLite LIMIT clause is used to limit the data amount returned by the SELECT
statement.
Syntax
Following is the syntax of LIMIT clause when it is used along with OFFSET
clause.
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever
column you are using to sort, that column should be available in the column-list.
Syntax
SELECT column-list
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2....columnN
ORDER BY column1, column2....columnN
You can use more than one column in the GROUP BY clause. Make sure whatever
column you are using to group, that column should be available in the column-list.
SQLite - HAVING Clause
HAVING clause enables you to specify conditions that filter which group results
appear in the final results.
The WHERE clause places conditions on the selected columns, whereas the
HAVING clause places conditions on groups created by GROUP BY clause.
Syntax
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
HAVING clause must follow GROUP BY clause in a query and must also precede
ORDER BY clause if used. Following is the syntax of the SELECT statement,
including HAVING clause.
There may be a situation when you have multiple duplicate records in a table.
While fetching such records, it makes more sense to fetch only unique records
instead of fetching duplicate records.
Syntax
DATA BINDING: The Data Binding Library is a support library that allows you
to bind UI components in your layouts to data sources in your app using a
declarative format rather than programmatically.
Step-by-Step Implementation
Step 1: Create a New Project
Open a New Project.
We will be working on Empty Activity with language such as Java. Leave all
other options unchanged.
Name the application at your convenience.
There will be two default files named activity_main.xml and
MainActivity.java.
Step 2. Enable DataBinding
Navigate to Gradle Scripts > gradle.scripts(module) and add the following
code to it.
Add the below code snippet to the build.gradle file to activate dataBinding
in the application:
buildFeatures
{
dataBinding = true
}
Step 3. Working on XML files
Navigate to the app > res > layout > activity_main.xml and add the below code to
that file.
Navigate to app > right-click > new > fragment > BlankFragment and name it as
“MainFragement”:
To read the file from the internal storage of device, java.io package
offers openFileInput() method which returns the instance
of FileInputStream class. To read the data from file call
the BufferedReader().readLine()
app creates files that other apps don't need to access, or shouldn't access. The
system provides the following locations for storing such app-specific files:
Internal storage directories: These directories include both a dedicated location
for storing persistent files, and another location for storing cache data. The system
prevents other apps from accessing these locations, and on Android 10 (API level
29) and higher, these locations are encrypted. These characteristics make these
locations a good place to store sensitive data that only your app itself can access.
External storage directories: These directories include both a dedicated location
for storing persistent files, and another location for storing cache data. Although
it's possible for another app to access these directories if that app has the proper
permissions, the files stored in these directories are meant for use only by your
app. If you specifically intend to create files that other apps should be able to
access, your app should store these files in the shared storage part of external
storage instead.
When the user uninstalls your app, the files saved in app-specific storage are
removed. Because of this behavior, you shouldn't use this storage to save anything
that the user expects to persist independently of your app. For example, if your app
allows users to capture photos, the user would expect that they can access those
photos even after they uninstall your app. So you should instead use shared storage
to save those types of files to the appropriate media collection.
The following sections describe how to store and access files within app-specific
directories.
Access from internal storage
For each app, the system provides directories within internal storage where an app
can organize its files. One directory is designed for your app's persistent files, and
another contains your app's cached files. Your app doesn't require any system
permissions to read and write to files in these directories.
Other apps cannot access files stored within internal storage. This makes internal
storage a good place for app data that other apps shouldn't access.
Keep in mind, however, that these directories tend to be small. Before writing app-
specific files to internal storage, your app should query the free space on the
device.
Your app's ordinary, persistent files reside in a directory that you can access using
the filesDir property of a context object. The framework provides several methods
to help you access and store files in this directory.
You can use the File API to access and store files.
To help maintain your app's performance, don't open and close the same file
multiple times.
The following code snippet demonstrates how to use the File API:
File file = new File(context.getFilesDir(), filename);
As an alternative to using the File API, you can call openFileOutput() to get
a FileOutputStream that writes to a file within the filesDir directory.
The following code snippet shows how to write some text to a file:
String filename = "myfile";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename,
Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
View list of files
You can get an array containing the names of all files within the filesDir directory
by calling fileList(), as shown in the following code snippet:
Filedirectory=context.getFilesDir();
File file = new File(directory, filename);
Accessing SD Card:
Open your SD card slot with a SIM tool or the end of a paperclip. Insert the SD
card (or the adapter containing the card) and close the slot. Go to Settings >
Storage > SD Card.
Next, scroll down – or search – until you find Storage, then tap on it. Finally,
select the SD card listed in the Portable storage section.