0% found this document useful (0 votes)
31 views47 pages

Unit4 MAD

Uploaded by

bhargavramkp02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views47 pages

Unit4 MAD

Uploaded by

bhargavramkp02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Unit4:

CREATING YOUR OWN CONTENT PROVIDER

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.

Creating a Content Provider


Following are the steps which are essential to follow in order to create a Content
Provider:
 Create a class in the same directory where the that MainActivity file resides
and this class must extend the ContentProvider base class.
 To access the content, define a content provider URI address.
 Create a database to store the application data.
 Implement the six abstract methods of ContentProvider class.
 Register the content provider in AndroidManifest.xml file using <provider>
tag.

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.

To insert a new row in the database of the content provider.


insert()
It returns the content URI of the inserted row.

This method is used to update the fields of an existing row.


update()
It returns the number of rows updated.

This method is used to delete the existing rows.


delete()
It returns the number of rows deleted.

This method returns the Multipurpose Internet Mail


getType() Extension(MIME)
type of data to the given Content URI.

As the content provider is created, the android system calls


onCreate()
this method immediately to initialise the provider.

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.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

Step 2: Working with the XML Files


Next, go to the activity_main.xml file, which represents the UI of the project.
This file contains a Relative Layout which contains three Edit texts for receiver
mail id, another for the subject of the mail, and last one for the body of the email,
and three TextViews for the label and a button for starting intent or sending mail:

Step 3: Working with the MainActivity File


In MainActivity Intent object is created and its action is defined to
ACTION_SEND to send an email, with Intent three extra fields are also added
using the putExtra function. These fields are:
 Email of receiver
 Subject of email
 Body of email

setOnClickListener is attached to a button with the intent object in it to make


intent with action as ACTION_SEND to send 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.

4. Skip the Billing Process


5. For integrating Google Map API, your machine’s SHA1 certificate is needed.
So to find SHA1 certificate, follow below steps:
 Open Command Prompt and go to your Java bin Folder
cd C:\Program Files\Java\jdk1.8.0_91\bin
 Give the following CMD command for getting Certificate Footprints:
keytool -list -v -keystore “%USERPROFILE%\.android\debug.keystore” -alias
androiddebugkey -storepass android -keypass android


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.

3. In Application Restrictions, select Android apps

4. Click on Add package name and fingerprint


5. Enter your app’s package name and the fingerprint which was found in above
steps and click Save button.

6. Insert the following in Project ->app ->src ->build.gradle ->dependencies


compile 'com.google.android.gms:play-services:11.6.0'

Getting location data:


Android devices can get location data from a variety of sources, including GPS,
networks, and other sources, and can use it in a number of ways:
 Google
Google uses location data to provide more relevant results in services like Maps,
Search, and Google Assistant.
 Location Manager
This module can provide location data for events and geofencing around points of
interest.
 Mock Location
This feature allows developers and users to simulate location data for testing, geo-
tagging, and other purposes.
 Web & App Activity
This setting can save location data from your device's general area and IP address
as part of activity on Search and Maps, and in your photos depending on your
camera app settings.
Here are some other ways to get location data on Android:
 LocationListener
This interface is part of the Android Locations API and receives notifications from
the LocationManager when the location has changed.
 Specify app permissions
In earlier versions of Android, the accuracy of location is controlled by whether an
app requests the ACCESS_FINE_LOCATION or
ACCESS_COARSE_LOCATION permission.

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

In your activity's onCreate() method, create an instance of the Fused Location


Provider
Get the last known location

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.

Set up for geofence monitoring

The first step in requesting geofence monitoring is to request the necessary


permissions. To use geofencing, your app must request the following:
 ACCESS_FINE_LOCATION
 ACCESS_BACKGROUND_LOCATION. if your app targets Android 10 (API
level 29) or higher
To learn more, see the guide on how to request location permissions.
If you want to use a BroadcastReceiver to listen for geofence transitions, add an
element specifying the service name. This element must be a child of
the <application> element:

Introduction to SQLite:

SQLite is an in-process library that implements a self-contained, serverless, zero-


configuration, transactional SQL database engine. It is a database, which is zero-
configured, which means like other databases you do not need to configure it in
your system.

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.

DML - Data Manipulation Language


Comma
Sr. nd &
No. Descript
ion

INSER
1 T
Creates
a record
UPDAT
2 E
Modifies
records
DELET
3 E
Deletes
records

DQL - Data Query Language


Sr.No
Command & Description
.

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.

Sr.No Command & Description


.
.backup ?DB? FILE
1
Backup DB (default "main") to FILE
.bail ON|OFF
2
Stop after hitting an error. Default OFF
.databases
3
List names and files of attached databases
.dump ?TABLE?
Dump the database in an SQL text format. If TABLE
4
specified, only dump tables matching LIKE pattern
TABLE
.echo ON|OFF
5
Turn command echo on or off
.exit
6
Exit SQLite prompt
.explain ON|OFF
7 Turn output mode suitable for EXPLAIN on or off.
With no args, it turns EXPLAIN on
.header(s) ON|OFF
8
Turn display of headers on or off
.help
9
Show this message
.import FILE TABLE
10
Import data from FILE into TABLE
.indices ?TABLE?
Show names of all indices. If TABLE specified, only
11
show indices for tables matching LIKE pattern
TABLE
.load FILE ?ENTRY?
12
Load an extension library
.log FILE|off
13
Turn logging on or off. FILE can be stderr/stdout
14 .mode MODE
Set output mode where MODE is one of −
 csv − Comma-separated values
 column − Left-aligned columns.
 html − HTML <table> code
 insert − SQL insert statements for TABLE
 line − One value per line
 list − Values delimited by .separator string
 tabs − Tab-separated values
 tcl − TCL list elements
.nullvalue STRING
15
Print STRING in place of NULL values
.output FILENAME
16
Send output to FILENAME
.output stdout
17
Send output to the screen
.print STRING...
18
Print literal STRING
.prompt MAIN CONTINUE
19
Replace the standard prompts
.quit
20
Exit SQLite prompt
.read FILENAME
21
Execute SQL in FILENAME
.schema ?TABLE?
22 Show the CREATE statements. If TABLE specified,
only show tables matching LIKE pattern TABLE
.separator STRING
23
Change separator used by output mode and .import
.show
24
Show the current values for various settings
.stats ON|OFF
25
Turn stats on or off
.tables ?PATTERN?
26
List names of tables matching a LIKE pattern
27 .timeout MS
Try opening locked tables for MS milliseconds
.width NUM NUM
28
Set column widths for "column" mode
.timer ON|OFF
29
Turn the CPU timer measurement on or off

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 (;).

SQLite ANALYZE Statement

ANALYZE;
or
ANALYZE database_name;
or
ANALYZE database_name.table_name;

SQLite AND/OR Clause

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;

SQLite ALTER TABLE Statement

ALTER TABLE table_name ADD COLUMN column_def...;

SQLite ALTER TABLE Statement (Rename)

ALTER TABLE table_name RENAME TO new_table_name;

SQLite ATTACH DATABASE Statement

ATTACH DATABASE 'DatabaseName' As 'Alias-Name';

SQLite BEGIN TRANSACTION Statement

BEGIN;
or
BEGIN EXCLUSIVE TRANSACTION;

SQLite BETWEEN Clause

SELECT column1, column2....columnN


FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;

SQLite COMMIT Statement

COMMIT;

SQLite CREATE INDEX Statement

CREATE INDEX index_name


ON table_name ( column_name COLLATE NOCASE );

SQLite CREATE UNIQUE INDEX Statement

CREATE UNIQUE INDEX index_name


ON table_name ( column1, column2,...columnN);

SQLite CREATE TABLE Statement

CREATE TABLE table_name(


column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);

SQLite CREATE TRIGGER Statement

CREATE TRIGGER database_name.trigger_name


BEFORE INSERT ON table_name FOR EACH ROW
BEGIN
stmt1;
stmt2;
....
END;
SQLite CREATE VIEW Statement

CREATE VIEW database_name.view_name AS


SELECT statement....;

SQLite CREATE VIRTUAL TABLE Statement

CREATE VIRTUAL TABLE database_name.table_name USING


weblog( access.log );
or
CREATE VIRTUAL TABLE database_name.table_name USING fts3( );

SQLite COMMIT TRANSACTION Statement

COMMIT;

SQLite COUNT Clause

SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;

SQLite DELETE Statement

DELETE FROM table_name


WHERE {CONDITION};

SQLite DETACH DATABASE Statement

DETACH DATABASE 'Alias-Name';

SQLite DISTINCT Clause

SELECT DISTINCT column1, column2....columnN


FROM table_name;

SQLite DROP INDEX Statement

DROP INDEX database_name.index_name;

SQLite DROP TABLE Statement

DROP TABLE database_name.table_name;


SQLite DROP VIEW Statement

DROP INDEX database_name.view_name;

SQLite DROP TRIGGER Statement

DROP INDEX database_name.trigger_name;

SQLite EXISTS Clause

SELECT column1, column2....columnN


FROM table_name
WHERE column_name EXISTS (SELECT * FROM table_name );

SQLite EXPLAIN Statement

EXPLAIN INSERT statement...;


or
EXPLAIN QUERY PLAN SELECT statement...;

SQLite GLOB Clause

SELECT column1, column2....columnN


FROM table_name
WHERE column_name GLOB { PATTERN };

SQLite GROUP BY Clause

SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;

SQLite HAVING Clause

SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);

SQLite INSERT INTO Statement


INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);

SQLite IN Clause

SELECT column1, column2....columnN


FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);

SQLite Like Clause

SELECT column1, column2....columnN


FROM table_name
WHERE column_name LIKE { PATTERN };

SQLite NOT IN Clause

SELECT column1, column2....columnN


FROM table_name
WHERE column_name NOT IN (val-1, val-2,...val-N);

SQLite ORDER BY Clause

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};

SQLite PRAGMA Statement

PRAGMA pragma_name;

For example:

PRAGMA page_size;
PRAGMA cache_size = 1024;
PRAGMA table_info(table_name);

SQLite RELEASE SAVEPOINT Statement

RELEASE savepoint_name;

SQLite REINDEX Statement


REINDEX collation_name;
REINDEX database_name.index_name;
REINDEX database_name.table_name;

SQLite ROLLBACK Statement

ROLLBACK;
or
ROLLBACK TO SAVEPOINT savepoint_name;

SQLite SAVEPOINT Statement

SAVEPOINT savepoint_name;

SQLite SELECT Statement

SELECT column1, column2....columnN


FROM table_name;

SQLite UPDATE Statement

UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];

SQLite VACUUM Statement

VACUUM;

SQLite WHERE Clause

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION;
Print Page

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.

SQLite Storage Classes

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.

SQLite Affinity Type


SQLite supports the concept of type affinity on columns. Any column can still
store any type of data but the preferred storage class for a column is called
its affinity. Each table column in an SQLite3 database is assigned one of the
following type affinities −
Sr.No
Affinity & Description
.
TEXT
1 This column stores all data using storage classes
NULL, TEXT or BLOB.
NUMERIC
2 This column may contain values using all five storage
classes.
INTEGER
3 Behaves the same as a column with NUMERIC
affinity, with an exception in a CAST expression.
REAL
4
Behaves like a column with NUMERIC affinity except that it
forces integer values into floating point representation.
NONE
5 A column with affinity NONE does not prefer one storage class
over another and no attempt is made to coerce data from one
storage class into another.

SQLite Affinity and Type Names

Following table lists down various data type names which can be used while
creating SQLite3 tables with the corresponding applied affinity.

Data Type 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).

Date and Time Datatype

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

Following is the basic syntax of sqlite3 command to create a database: −

$sqlite3 DatabaseName.db

Always, database name should be unique within the RDBMS.

SQLite ATTACH DATABASE:

Syntax

Following is the basic syntax of SQLite ATTACH DATABASE statement.

ATTACH DATABASE 'DatabaseName' As 'Alias-Name';


The above command will also create a database in case the database is already not
created, otherwise it will just attach database file name with logical database
'Alias-Name'.

SQLite - DETACH Database


SQLite DETACH DATABASE statement is used to detach and dissociate a
named database from a database, If connection which was previously attached
using ATTACH statement. If the same database file has been attached with
multiple aliases, then DETACH command will disconnect only the given name and
rest of the attachment will still continue. You cannot detach
the main or temp databases.
If the database is an in-memory or temporary database, the database will be
destroyed and the contents will be lost.
Syntax

Following is the basic syntax of SQLite DETACH DATABASE 'Alias-Name'


statement.

DETACH DATABASE 'Alias-Name';

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

Following is the basic syntax of CREATE TABLE statement.

CREATE TABLE database_name.table_name(


column1 datatype PRIMARY KEY(one or more columns),
column2 datatype,
column3 datatype,
.....
columnN datatype
);

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.

SQLite - DROP Table


SQLite DROP TABLE statement is used to remove a table definition and all
associated data, indexes, triggers, constraints, and permission specifications for
that table.

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 Query

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 Query

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

- (Subtraction) Subtracts the right hand operand a - b will


from the left hand operand give -10

* Multiplies values on either side a * b will


(Multiplication) of the operator give 200

Divides the left hand operand by b / a will


/ (Division)
the right hand operand give 2

Divides the left hand operand by b % a


% (Modulus) the right hand operand and will give
returns the remainder 0

SQLite Comparison Operators

Assume variable a holds 10 and variable b holds 20, then SQLite comparison
operators will be used as follows

Show Examples

Operator Example
Description

Checks if the values of two operands (a == b)


== are equal or not, if yes then the is not
condition becomes true. true.

Checks if the values of two operands


(a = b) is
= are equal or not, if yes then the
not true.
condition becomes true.

Checks if the values of two operands


(a != b)
!= are equal or not, if the values are not
is true.
equal, then the condition becomes true.

Checks if the values of two operands


(a <> b)
<> are equal or not, if the values are not
is true.
equal, then the condition becomes true.
Checks if the values of the left operand
is greater than the value of the right (a > b) is
>
operand, if yes then the condition not true.
becomes true.

Checks if the values of the left operand


is less than the value of the right (a < b) is
<
operand, if yes then the condition true.
becomes true.

Checks if the value of the left operand


(a >= b)
is greater than or equal to the value of
>= is not
the right operand, if yes then the
true.
condition becomes true.

Checks if the value of the left operand


is less than or equal to the value of the (a <= b)
<=
right operand, if yes then the condition is true.
becomes true.

Checks if the value of the left operand


is not less than the value of the right (a !< b)
!<
operand, if yes then the condition is false.
becomes true.

Checks if the value of the left operand


is not greater than the value of the right (a !> b)
!>
operand, if yes then the condition is true.
becomes true.

SQLite Logical Operators

Here is a list of all the logical operators available in SQLite.

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 Bitwise Operators


Bitwise operator works on bits and performs bit-by-bit operation. Following is the
truth table for & and |.

SQLite – Expressions

An expression is a combination of one or more values, operators, and SQL


functions that evaluate to a value.

SQLite - Numeric Expression

These expressions are used to perform any mathematical operation in any query.
Following is the syntax −

SELECT numerical_expression as OPERATION_NAME


[FROM table_name WHERE CONDITION] ;
Here, numerical_expression is used for mathematical expression or any formula.
Following is a simple example showing the usage of SQLite Numeric Expressions.

sqlite> SELECT (15 + 6) AS ADDITION


ADDITION = 21

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

Consider the basic syntax of the SELECT statement as follows −

SELECT column1, column2, columnN


FROM table_name
WHERE [CONDITION | EXPRESSION];

Following are the different types of SQLite expressions.

SQLite - Boolean Expressions

SQLite Boolean Expressions fetch the data on the basis of matching single value.
Following is the syntax −

SELECT column1, column2, columnN


FROM table_name
WHERE SINGLE VALUE MATCHTING EXPRESSION;

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.

sqlite> SELECT COUNT(*) AS "RECORDS" FROM COMPANY;


RECORDS = 7
SQLite - Date Expressions

Date Expressions returns the current system date and time values. These
expressions are used in various data manipulations.

sqlite> SELECT CURRENT_TIMESTAMP;


CURRENT_TIMESTAMP = 2013-03-17 10:43:35
SQLite - WHERE Clause
SQLite WHERE clause is used to specify a condition while fetching the data from
one table or multiple tables.

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.

SELECT column1, column2, columnN


FROM table_name
WHERE [condition]

SQLite - AND & OR Operators


SQLite AND & OR operators are used to compile multiple conditions to narrow
down the selected data in an SQLite statement. These two operators are
called conjunctive operators.

These operators provide a means to make multiple comparisons with different


operators in the same SQLite statement.

The AND Operator


The AND operator allows the existence of multiple conditions in a SQLite
statement's WHERE clause. While using AND operator, complete condition will
be assumed true when all the conditions are true. For example, [condition1] AND
[condition2] will be true only when both condition1 and condition2 are true.

Syntax

Following is the basic syntax of AND operator with WHERE clause.

SELECT column1, column2, columnN


FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
You can combine N number of conditions using AND operator. For an action to be
taken by the SQLite statement, whether it be a transaction or query, all conditions
separated by the AND must be TRUE.
Example

Consider COMPANY table with the following records −

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where AGE is greater than
or equal to 25 AND salary is greater than or equal to 65000.00.
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >=
65000;

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
The OR Operator

The OR operator is also used to combine multiple conditions in a SQLite


statement's WHERE clause. While using OR operator, complete condition will be
assumed true when at least any of the conditions is true. For example, [condition1]
OR [condition2] will be true if either condition1 or condition2 is true.

Syntax

Following is the basic syntax of OR operator with WHERE clause.

SELECT column1, column2, columnN


FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
You can combine N number of conditions using OR operator. For an action to be
taken by the SQLite statement, whether it be a transaction or query, only any ONE
of the conditions separated by the OR must be TRUE.

Example

Consider COMPANY table with the following records.


ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where AGE is greater than
or equal to 25 OR salary is greater than or equal to 65000.00.
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >=
65000;

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0

SQLite - UPDATE Query


SQLite UPDATE Query is used to modify the existing records in a table. You can
use WHERE clause with UPDATE query to update selected rows, otherwise all the
rows would be updated.
Syntax

Following is the basic syntax of UPDATE query with WHERE clause.

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

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

Following is the basic syntax of DELETE query with WHERE clause.

DELETE FROM table_name


WHERE [condition];
You can combine N number of conditions using AND or OR operators.

SQLite - LIKE Clause


SQLite LIKE operator is used to match text values against a pattern using
wildcards. If the search expression can be matched to the pattern expression, the
LIKE operator will return true, which is 1. There are two wildcards used in
conjunction with the LIKE operator −
 The percent sign (%)
 The underscore (_)

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

Following is the basic syntax of % and _.

SELECT FROM table_name


WHERE column LIKE 'XXXX%'
or
SELECT FROM table_name
WHERE column LIKE '%XXXX%'
or
SELECT FROM table_name
WHERE column LIKE 'XXXX_'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX_'
You can combine N number of conditions using AND or OR operators. Here,
XXXX could be any numeric or string value.
SQLite - GLOB Clause

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

2 WHERE SALARY GLOB '*200*'


Finds any values that have 200 in any position
WHERE SALARY GLOB '?00*'
3 Finds any values that have 00 in the second and third
positions
WHERE SALARY GLOB '2??'
4 Finds any values that start with 2 and are at least 3
characters in length

5 WHERE SALARY GLOB '*2'


Finds any values that end with 2
WHERE SALARY GLOB '?2*3'
6 Finds any values that have a 2 in the second position
and end with a 3
WHERE SALARY GLOB '2???3'
7 Finds any values in a five-digit number that start with
2 and end with 3

SQLite - LIMIT Clause

SQLite LIMIT clause is used to limit the data amount returned by the SELECT
statement.
Syntax

Following is the basic syntax of SELECT statement with LIMIT clause.

SELECT column1, column2, columnN


FROM table_name
LIMIT [no of rows]

Following is the syntax of LIMIT clause when it is used along with OFFSET
clause.

SELECT column1, column2, columnN


FROM table_name
LIMIT [no of rows] OFFSET [row num]
SQLite engine will return rows starting from the next row to the given OFFSET as
shown below in the last example.

SQLite - ORDER BY Clause


SQLite ORDER BY clause is used to sort the data in an ascending or descending
order, based on one or more columns.
Syntax

Following is the basic syntax of ORDER BY 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.

SQLite - GROUP BY Clause


SQLite GROUP BY clause is used in collaboration with the SELECT statement to
arrange identical data into groups.

GROUP BY clause follows the WHERE clause in a SELECT statement and


precedes the ORDER BY clause.

Syntax

Following is the basic syntax of GROUP BY clause. GROUP BY clause must


follow the conditions in the WHERE clause and must precede ORDER BY clause
if one is used.

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

Following is the position of HAVING clause in a SELECT query.

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.

SELECT column1, column2


FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

SQLite - DISTINCT Keyword


SQLite DISTINCT keyword is used in conjunction with SELECT statement to
eliminate all the duplicate records and fetching only the unique records.

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

Following is the basic syntax of DISTINCT keyword to eliminate duplicate


records.
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]

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”:

Step 4. Working on Java files


Navigate to the MainActivity.java file
Navigate to the MainFragment.java file and use the following code in it.

Reading/Writing local data:


To read and write the data from (into) the file, Android provides openFileInput()
and openFileOutput() methods respectively. When the users uninstall its
application from the device, its internal storage file will also be removed.

Write to File in Internal Storage

To write the file in internal storage of device, java.io package


offers openFileOutput() method which returns the instance
of FileOutputStream class. To write the data into the file call
the FileOutputStream .write() method.

val file:String = fileName.text.toString()


val data:String = fileData.text.toString()
val fileOutputStream:FileOutputStream
try {
fileOutputStream = openFileOutput(file, Context.MODE_PRIVATE)
fileOutputStream.write(data.toByteArray())
}catch (e: Exception){
e.printStackTrace()
}

Read File content from Internal Storage

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()

var fileInputStream: FileInputStream? = null


fileInputStream = openFileInput(filename)
var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)

val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)


val stringBuilder: StringBuilder = StringBuilder()
var text: String? = null
while ({ text = bufferedReader.readLine(); text }() != null) {
stringBuilder.append(text)
}
//Displaying data on EditText
fileData.setText(stringBuilder.toString()).toString()

Accessing the internal file system:

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.

Access persistent files

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.

Access and store files

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);

Store a file using a stream

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:

Array<String> files = context.fileList();

Create nested directories

You can also create nested directories, or open an inner directory, by


calling getDir() in Kotlin-based code or by passing the root directory and a new
directory name into a File constructor in Java-based code:

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.

Accessing an SD card via Settings


If you can’t find the Files app, or just prefer another route to the SD card, then
here’s what to do. Open the Notifications window by swiping down from the top of
the screen, then tap on the Settings icon (the one that looks like a
cog). Alternatively, you can find the Settings app and tap that instead.

Next, scroll down – or search – until you find Storage, then tap on it. Finally,
select the SD card listed in the Portable storage section.

You might also like