0% found this document useful (0 votes)
162 views12 pages

MAD Unit 4

The document discusses different ways to store data persistently in an Android application, including using internal storage, external storage, shared preferences, and SQLite databases. It provides examples of creating, reading, and searching for files in the application's internal storage folder.

Uploaded by

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

MAD Unit 4

The document discusses different ways to store data persistently in an Android application, including using internal storage, external storage, shared preferences, and SQLite databases. It provides examples of creating, reading, and searching for files in the application's internal storage folder.

Uploaded by

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

St or in g the Data

4 Persistently

Syllabus . . . .
. the Data Storage Optio ns, Uszng the internal storage, uszng the external storage, using the
JnJroducing . .
e Work ing with content provider.
sQLile Databas ,
-Contents
4. 1
storage Data Folder
al Storage
4_2 Using /ntem
Storage
4_3 Using External
4_4 Shared Preferences
4.5 SQUte
4.6 Content Provider
4. 7 Handling Database in Android
4.8 Short Questions and Answers
4.9 Multiple Choice Questions
~M ~o b~ il~ e!_ A~ pp
I ~l~ ic~
t at~ io~ n_ 4 _2
:D ~e ~v e~ o~ p~ m~ e~ n~ --- --~Storing the Data PersistenN"
-= --- --- --- --- --- --- .!_
B l Storage Data Folder
Store application-specific data
• The application dat a folder is a
special hid den folder tha t yo ur ap
store application-specific data, suc h p can use to
as configuration files.
• The application dat a folder is aut
omatically cre ate d wh en yo u att em
file in it. Use this folder to store any pt to create a
files tha t the use r sho uld n't dir ect
with. ly interact
• This folder is only accessible by
yo ur application and its con ten ts are
the use r and from oth er Drive apps. hid de n from
• The application dat a folder is del
eted wh en a use r uni nst all s yo ur
MyDrive. Users can also delete yo ur ap p fro m their
app 's dat a folder ma nua lly .
Il l• Application Data Folder Scope
• Before you can access the app lic
ati on dat a folder, yo u mu st req ues
htt ps: / /w ww .go og lea pis .co m/ au th/ t acc ess to the
dri ve. app dat a scope. Fo r mo re
about scopes and ho w to req ues t acc inf orm ati on
ess to the m, ref er to Au the nti cat e
yo ur use rs.
li fj Creating File in App Data Folder
• To create a file in the applicatio
n dat a folder, spe cif y app Da taF old
pro per ty of the file and use the file er in the parents
s.create me tho d to up loa d the file
to the folder.
• The following example sho ws
ho w to ins ert a file int o a fol der
library : usi ng a client

File fileMetadata = new FileQ;


fileMetadata.setN ame("con fig.jso n9
);

file Me tad ata .setPa:rents(Collections


. . . .
.singletont· t(ii . D · ·
Java.10.FilefilePath = new Jav lS ap p ata Fo lde r'))
a io File('1.Q1-s/ . nfi ·. .
·
·
Fil eC ont ent me dia Co nte nt = new · · ~ co g.Json")· · '
Fil eC t (u .. '
File file = driveService .files().creat on an t app lic ati on /' .. fi p
e(fileMetad . . Json , le ath ):
.se tFi eld s('1id11 )
ata, me dia Co nte nt)
.ex ecu te( );
Syf ;te, n.o ut,p.rintlnC'Fil e ID: " + file .ge tld ());
(I ii Search for Files in App Data Folder
• To search for files i.n ithe
app lic ati on dat a
app Da taF old er and use the file s.li fol der , set 1-1...e
st m e tho d . '-HJ spaces field to
4 3 _ _ _ _ _ __:S::to:..'.ri~ng~t~he~D~a~ta~P,~e~rs~is~te~n'!!!_tly
_ _ _ _ _ _ __-_ _
~s::t1.:.·on_D_e_v_el_op_m_e_n_t

le sho ws ho w to sea rch for files in the application data folder


, The following examp
using a client lib rar y :
. ···.,;
, ~~miilite,. -. . :.tanv~seivi6e-:tiiestJ:n~ y, . ~-· .. .,:
~ ·:satiJi~~s(~a,ppD at~ol~erlr- ,·. . .

lfJ Using Internal Storage


al File-
Android Read Write Data To Intern
be sav ed in int ern al sto rag e (ROM) , external storage(SD card)✓
• Android data can
se.
shared preferences or SQLite databa
id is bas ed on Lin ux, and roi d file system is Linux based also.
• Andro
nitor and
id stu dio pro vid e and roi d dev ice monitor tool for you to mo
• Andro
ice and you r PC.
transfer files between and roi d dev
e
int ern al dat a file s is sav ed in /da ta/ da ta/ <your app packag
• All android app saved in
folder like bel ow . Fo r exa mp le, my app data internal file is
name>
I dat a/ da ta/ com.dev2qa.example folder.
.
der un der the package name folder
• There are files and cache sub fol return this
s folder • and roi d.c ont ent .Co ntext's getFilesDir() method can
l. File
general files.
folder. This folder is used to save
- and roi d.c ont ent .Co nte xt's get CacheDir() method can return this
2. Cache folder
cached files .
folder. This folder is used to save roid
ice int ern al sto rag e spa ce is low , cache files will be removed by and
• When dev
ke int ern al sto rag e spa ce bigger . Generally you nee d to
os automatically to ma
not
sed cac he file s in cod e tim ely, totally cache file size is better
delete the unu
more than l MB .
QJ Uaing External Storage
Android ext.mar Storage d),
e ( RO M ) , extern.al stoTage(SD car
• Android data can be saved in intern al storag
shared pre fer enc es ot SQ Llt e d ata bas e. d _,.
ulg \Ua twn
and sav e dat a, rea cor
• An-L
UJ'O ld ext ern al sto rag e can be use d to \svrite
falh l'k .
t •I.. I

o sto re app lica tio n c d ta, u tere s no


f \,,f'- al.s
I
.,,.~rna.J E>torage suc h as SD card can _ __ _
e d upo n file~ you sav e to the e.xt ema.1 s tor age_. _ _ _ _
---- --~ ~ o r c
- - - - -- -
________ _--:..
~M~ob~ile~A~p~p~lic~a~tio~n_:D~e~ve~lo~pm~en~t _ _ _ _ _ _"'_:_-_ ..,..:___ _ _ _ _

• In general there are two types of External Storage :


1. Primary External Storage: In built shared storage which is
"ac~essible by the
· a USB cable and mounting it as a drive on a host

user by p1uggmg
computer". Example: When we say Nexus 5 32 GB.
2. Secondary External Storage : Removable storage. Example : SD Card
• All applications can read and write files placed on the external
storage and the
can
user can remove them. We need to check if the SD card is available and if we
we
write to it. Once we've checked that the external storage is available only then
can write to it else the save button would be disabled.
and
• Firstly, we need to make sure that the application has permission to read
add
write data to the users SD card, so lets open up the AndroidManifest.xml and
the following permissions :

• Also, external storage may be tied up by the user havin g moun ted
it as a USE
is no!
storage device. So we need to check if the external storage is available and
read only.
extern~
getExternalStorageState() is a static method of Environment to deter mine if
false we've
storage is presently available or not. As you can see if the condi tion is
disabled the save button.
1. Environment.getExternalStorageState() : returns path to intern al SD moun
t point like
"/mnt /sdca rd".
2. getExterna/FilesDir() : It returns the path to files folder inside
And~ oid/~ ata/da ta/app licati on_pa ckage / on the SD card. It is used to store
any
reqwred_ files. for your app (like images down loade d from web or cache files).
Ono
the app 1s urunstalled, any data stored in this folder is gone too.

IIJ Shared Preferences


allow you to read and wr·t all amounts of pnnut . dal
. . ive
• Shared preferences. 1 e sm
(as key /valu e pairs) to a file on the devic e storag e.
. .
• The SharedPreference class prov·1d APIs for gettin g a hand le to a preference W
and for read• .. es
mg, wntin g, and mana ging this data.
• The shared preferences file itself is
accessible to (shared with) all th mana ged by the Andr oid framework, ~ 0
howe ver, shared w·th . e comp onent s of your app. That data tS
1 or accessible to any other ap ps.
./;cation Development 4 _5
--~~-
!tfobileAPP~:_..-- - - - - - - - -----~St~orlnr,ng the Data P .
. ~ ~ ers,stentty
e data you sav e to sha red pre ferences is differ
• Th ent from the data m.
activity state. the saved
.
The data in the activity instance sta te is retained across activity instan .
• ces m the
same user session.
. ns e
use r sessio
Shared preferences per sis t across if
· your app is killed and
• dev ice is reb oot ed. ' ven
restarted or if the
d
, use shared preferenc. es on ly wh en laryou ger
nee to save a small amount data as
simple key / v alue pai rs. To ma nag e amounts of persiS!ent app data use the
ds suc h as SQ L dat aba ses .
other me tho

ferences
- Creating Private and Shared Pre

, Individual activities . can hav e the ir ow n pri vate pref erences. These preferences are
. th ...
for the .sp eci fic Ac tiv ity on ly an d are no t shared WI·th o er actiVIties wit hin the
appIica tion.
of private preferences.
• The activity get s on ly on e gro up
activity's private preferences :
• The following cod e ret rie ves the

.: i 1 1 ! 1 :ii!!~1W!:JA~);
red pre fer enc es by nam e from any activity in the application .
• You can access sha
it to the nu mb er of dif fer ent shared preferences you can create .
There is no lim
e sha red pre fer enc es cal led Us erNetworkPreferences and another
You can have som
called Ap pD isp la y Preferences.
• How you organize sha red prefer
ences is up to you, the developer .
variable (in a base class
ur preference nam e as a
• How ever/ you wa nt to dec lar e yo ulti 1 cti vi ties · For example
nam e across m Pe a
or ucader) so that you can reuse the
1. _

CE_FILENAME • •A,ppPTe&' ;
~l lc Btatic 6- 1 StriDa PREFEREN

• SQLlte ~ management
I d ata b
provi·d_es a rel aho na
• ·SQ1Y~
_· tw.
is a sof tv.1a1e lib rar y that
S\'S tem
.gh •ght in terms of setup, database administ ration
• The lite in SQLlte means li t we1 ,
and required resoq.rce.
• A SQLlte database is a good storage so1ution w
· hen you have structur ed data ~ t
you need to store persistently and access, search, and change frequent ly.
• SQLlte is self-contained means 1t· · · · al support from the operating
reqwres nurum
system or external library.
• This makes SQLite usable in any environments especially in embedd ed devices
like iPhones, Android phones, game consoles, handhel d media players, etc.
• SQLite is developed using ANSI-C. The source code is available as a big sqlite3.c
and its header file sqlite3.h.
• If you want to develop an application that uses SQLite, you just need to drop
these files into your project and compile it with your code.
• SQLlte databases are very lightweight. Unlike other database systems , there is no
configuration, installation required to start working on an SQLite database .
• :'11en you use a SQLite database, all interactions with the database are through an
instance of the SQLiteOpenHelper class which executes your requests and manages
your database for you.

• :n,e ~droid SQLite Database requires very little memory (around 250kb), which
IS available on all android devices.

• Every device has an inbuilt support for SQLite database which . .


managed on android right from its creation, executio n to q,uPrvin 18 automat ically
• SQL ·te • - , ...... Lg up process.
l IS an open source database, available on eve .
supports standard relations database featur lik S ry android databas e. It
tate · e QL syntax tr
s ments. SQL1te is considerably, the Ii es, h . , ansactio ·
ns & SQL
most of the SQL commands don't run SQgLt~r version of SQL database, where
• . . on ite database .
Once SQL1te is in place it is .
availabI . . , importa nt to ensure th t
em SQLite; only then can it b a a feature or command is
• Th B . e executed .
e as1c Advantages of SQL't .
1 It' Ii I e .
. s a ght weight database
2. Requires very little m
emory
3. An AutomaticaU
• The SQLite suppor ts~managed database
1. Text(like stnn ) y three Datatypes :
g - for storm
2. Integer(like int) f g data type store.
3 - or storing .
. ReaJ(Jike double) - £ . integer Prirnary key.
---- or storm~ ln .... _
CJ"tJnh"
.. c
·•I> other d atab ase m anag eme n t syste h
• . ms, t ere is no C .
. and in SQLite. In SQL1te, here is how y
cornni . REATE DATABAS
ou can create a ne . :e
·rnplest way to crea te a new SQLitcDat b .
'{he st w database :
• se the opcn OrC reate Duta base() meth od ofa aBe mstance

f
to O or your application .
unP°1' pdrOld,d&W>Ue,1qllteBOLiteDatabe.ae; your apphcation contex . u,
t, hke this •
•· ·teDatabasemDe.tehase:
soL>tablle • openOrCreateDatabase(
tnD• · tab81 e·db" ,
~ y ,qU.te_da .
sQLiieDatabase.CREATE_IF_NECESSARY;
null):
ED content Provider
• A content prov ider man ages access to a cent ral
. . . . repository of d t A . .
art of an And roid appl a a. provider IS
P icati on, whic h often prov ides its own UI f
the data. or working with
.

• Content prov ider s are prim arily inte nded to be used


by other applications, which
access the prov ider usin g a prov ider client object.
• Together, prov ider s and prov ider clients offer a
consistent, stan dard interface to
data that also hand les inter -pro cess com mun icati on and
secure data access.
• A content prov ider pres ents data to external appl
ications as one or more tables
that are similar to the table s foun d in a relational database
.
• A row repr esen ts an insta nce of som e type of
data the provider collects, and each
column in the row repr esen ts an indi vidu al piece of
data collected for an instance.
• Typically you wor k with cont ent prov ider s in one of
two scenarios; you may want
to implement code to acce ss an exis ting cont
ent prov ider in another.
• A conte nt prov ider coor dina tes access to the data
storage layer in your application
for a num ber of di ffere nt APls and com pone nts as
illustrated in Fig. 4.6.1.
• The content prov ider and othe r com pone nts include :
l . Sharing access to your appl icati on data with othe
r applicati ons
2. Sending data to a wid get
3. Rt tu rnin ~ cust om sear ch sugg estio ns fo r your appl
ication throu gh the
search framewor lic usin g SearchRecentSuggestionsProvid
er.
4. '-. ~1tchruni1ing appl icati on data with your L~ing an
server
1rnpl~men tano n of Abs.
tract Thre aded.SyncAdapter
s
-- Load u,tS data m your Ul uim g a Cur&orLoader

1[GHNICAI PIJBLJCA. TIONS~ · All up f/)11.1-'1 fOf N~


-~
AbstractThreadedSyncAdapter Cursorloader

Widgets

Other applications
ContentProvider

Search

Data storage Data storage

Fig. 4.6.1

(II ■ Content Provider Classes


• A content provider in Android shares data between applications. Each applicatior,
usually runs in its own process.
• By default, applications can't access the data and files of other applications.
• You can make preferences and files available across application boundaries Wifr
the correct permissions and if each application knows the context and path.
• This solution applies only to related applications that already know details abo~
one another.
• In contrast, with a content provider you can publish and expose a particular datt
type for other applications to query, add, update, and delete, and thOi
applications don't need to have any prior knowledge of paths, resources, or wrr
provides the content.
• The canonical content provider in Android is the contacts list, which provide
names, addresses, and phone numbers.
• You can access this data from any application by using the correct URI and
series of methods provided by the Activity and ContentResol ver classes to retrie1
and store data.

(1:fj Deleting Database Records


1
• The data modification clauses in SQLlte are INSERT, UPDATE, and DELf
statements. It is used for inserting new rows, updating existing values, or delet!r
rows from the database.

TECHNICAL PUBLICATIONS® - An up thrust for knowledge


Y' pficat1on
. :.:::_:__~--- - --- --=- --- --- · oevetopment 4-9
t
,iotJile AP, Storing the D
rrr
a a Persistently
· remove records from the datab
you can ase using the rem0 ()
• () method takes few argume nts. ve method.The
reIJ'love
. g null to the WHERE clause deletes all records within th
, passin .
. le, this ~~~.~~ .~~~l .,~~~~t~s all records within the e table. For
authors.~{:n.1/dl\.rl--..;t1t~,, :.c =>.'-..:)1/f;'..J%L'K:,!'' n;;·;,; ,.., t~~~e called thl authors .
~r:Z:~~=~, ;~:;:;~·::::: ~~;==
eX~~~~"'Ki/4.h ....ii-l >

k=
1

The following function takes a parameter book.Id and


, th . .d deletes the record
rresponding to at uruque I (primary key) within the t bl

, You need not use the primar y key (id) to delete records; the wm~··":~:::: ·:
entirely up to you. For instance, the following function deletes all book records in
the table.

·a .r ···--'
. . . . •. . . ·-· .,. . . .• . .•...•...... . -. -·-·-·-•...... .. . . . . ·~-·-·.·.•.•-. ·•.:::.:.-.:.,.•:.::-:_ ·-·-•............. ·.. ·..· ;
·.. ·=:-:•:.:::::;: • • :,:,:,:,'.·',·.·:.•'·':

} .... • .
• , ',·
'·'.'·.'·.'.·•,·,...•.,·,. ·.··.•.·•.,.··.·.·.=.,·.:.:.·...·,'·,.'.,.·,·.·,.' ..',:.,:,:••.'.:.·.'·

. ..
' ·:'.:,·.:.·.·.'•.:.,.' ·,' ,:.,,·,,·,:.,.' .,'.:
..:,..·,:,'•.:.,,·,.::,:.·::...,•:.,.' ,'..','....

. :::::.::::t:=:::::::::
:•:•:::·::=::::::,:,;:::,::. . .
::::: /::::::=:=~·== :=: ~:=::-\:it\\-:::.~:=:=:::.::::J:::=:::::://J?:AiJ@( MJ:f/f?f. . .:::)?\:\(\;
.:,:,:;:,::::::::,•:.:,:::::::c:::::::·::,:;: . , ........ ·•· .
:\t{=/\{/t://}(~ :)/:i/r··· ·· ./ ✓

DJ Handling Database in Android


• In the same way that you retriev e data from a provider, you also use the
interaction betwee n a provid er client and the provide r's ContentProvider to modify
data.

• You call a method of Conten tResolv er with argume nts that are passed to the
corresponding metho d of Conten tProvid er.
• The provider and provid er client automa tically handle security and inter-process
communication.

QI Inserting Data
• To insert data into a provid er, you call the ContentResolver.insert() meiliod . This
th31
method inserts a new row into the provid er and returns a content URI for
row.
Mobile Application Development 4- 10

,
•.·-:;:-: :-·.·= - __ _ ;{f. i?.. :.;:::,.::....=·:{:J;./~
=._•••.:. •/_:_;_·;,•_/.t_:!_i._•_
' ......... :(:)t;::::=\/:_
.-.. .. '
::-.:::;::: .... ... -.- ..'_: _
>?tf:.-.:
...•. .-. .-:.. ·.-:>· :> ··::;:• :-:-·-· •.-.-:-: :_ :,.. •.
::=·: ..::::- • _-_-::::···-··.:=:· ·,•::·.:-:·::·:: . ::;:/•--::_.;:=·
•,• •,• · .· ..-.-.- .·.•.·.•·-··:-t=·=· ./ \:::/=::):==:-. -· :·:·:-:..•:•··..
.:·::=: i-::\\i/·/ \?\:. :/:. /~\:;//:;;//\:\:. :··:;::.>;::" ·,:..;.
: hl;h;~,sinti i,
::-: <;:;:•·-~-:-: / ( \\:: :; .} /

le ContentValues obj~~:
• The dat a for the new row goes into a sing
in this object don't need to have llie
in form to a one-row cursor. The columns
ify a value at all, you can set a
sam e dat a type, and if you don't want to spec
col um n to null using ContentValues.putNull().
because this column is maintained
• The sni ppe t doesn't add the _ID column,
value of _ID to every row that ~
automatically. The provider assigns a unique
table's primary key.
add ed. Providers usually use this value as the
tifies the newly-added row, with the
• The con ten t URI retu rne d in newUri iden
following form at :
;:::::+t\:f}t:f§:\- l®n~pt;tZ.iifitin~~Pn$.XYLW<->t4@l~~l.tt£v.~u'~'>: s:;:.::::1::: ,:;I::Z'/,,:;":;'.;::;;;iMo;t:~;~{:7st :',prov
:i::::;:::::;::::~
iders can detoo
new row.
• The <id_value> is the contents of _ID for the
n perform the requested operatioo
this for m of con ten t URI automatically and the
on tha t par ticu lar row.
To get the val ue of _ID from the retu rne d Uri
, call ContentUris.parseld().

lf fj Updating Data
. h th e up d ated values jU51Th~
.ect w1t
s obJ
• To upd ate a row , you use a Con ten tVa lue · · ·
• n cnt ena 1ust as you do with a query.
ctio
you do wit h an insertion, and sele
d vou use is Con ten tRe sol ver .update().
:.-<:::·:~.:=::/;\; .:·(·

. .;: -· -__ ~, ·· ·.. t)(}:ifirii~\~~it::.ii{>~~: \t:~t:·=:r


·.·•.·.....•..·.•.:.,•,·· .;·
· . .• :·.
.•.• :•.·•.·...
.;.:·•,;
••.· • :.:~:,··.·,.:::.•,·.:.··
··.•·.·.·•.··.:.·.•.• ·•..••.... ..·...•·.·.::....
. ,·.•.·, ·· ....:...·•...·.:··•.··...
·.•.:,·:··•.:•:: : • •.

-
• You should also sanitize user input when you call ContentResolver.update().

OIJ Deleting data


• Deleting rows is similar to retrievi ng row data: you specify selection criteria for
th
e rows you want to delete and the client method returns the number of deleted
rows.
• Th
r e followmg snippe t d e 1etes rows w h ose app1'd matches "user " . The method
turns
e ilie number of deleted rows .
// Defines .. , . . .
va1 sel . aele.ction ontena for the rows you want to delete
vai sei::on Clause :;;:: "${UserDictionary.Words.LOCALE} LIKE 7'
0
nArgs: Array< String> == arrayOf ('\iset')
// D ~-
e~1es a Vari.ab!
var rowsDeL · e to contain the number of rows deleted
8 ted: Int= O

TECHNICAL PUBLICA TIONS® - An up thrust for knowledge


Storing the Data Persistently
Mo bil e Application De ve lop me nt 4- 12

\
• Yo u sh ou ld al so sanitize us er in pu t wh
en yo u call ContentResolver.delete() . I

You might also like