Introducing the Data Storage Gerba a m
nisms for data persistence. a
Android platform provides multiple mecha piace Ths ect pnd on
Aer edch asthe amount of data to be stored, fequency of data accessiti =npuston
er ama ah acre an ey
Fare rea factor can affect the selection of the mechanism. For example if YOu WARt to soe
aoe ene isevaluesin your application, then the shared preference mechanism canbe used. Hower
sere errtoive your application data niles, then you can use internal or external storage mechanisms,
“The different data storage options or mechanisms are as follows:
‘The preferences
The internal storage
The external storage
The SQLite database
The content providers
Let us explore each ofthese options in deta
Using Preferences
“The simplest mechanism to store the user data for long term is the preferences system. Inthe Android platform,
the activities and applications can store user preferences in the form of key/value pairs. When we sa that te
user preferences are being stored, it implies that the user-configuration details, such as the setting, wit
preference, sort order for alist or the last website accessed by the user, are recorded. Note that the preferences
‘an be stored either fra single activity or for multiple activities of an application
You can access the user preferences by using the get Preferences (), getsharedPretei
gerDerauitsharedPreferences|) method. The getPreferences() method is used within you
Activiey and allows you to access actviy-specific preferences. The get SharedPreferences () methads
also used within the Act ivi ty cass or in other application context and allows you to access applicatonte
Preferences. The getDe faultSharedPreferences() method allows you to retrieve the shared prelerencesit
‘elation tothe overall Android preference framework.
The Android SDK provides the SharedPreferences class to facilitate you to save and fetch the persis!
key/value pairs of primitive data types. The SharedPre ferences class allows you to save the values o te
following primitive datatypes
ecoee
ces)
2 boolean
2 oat
230ould note ha the data any ofthe preceding dats typos wt per ames umes emo even afer
ication has heen led You can te ether of Uw along tthe retrieve Ue ata of the
3 The getsharearreferences() method: Aliws you to work with mule prferenies es Fas He
‘Nena through ram. which provide asthe tnt parameter value
3 The getPreferences () method: Allows you to work with he singe preference fle fr your ASE ty
[ass You can avoid providing a name forthe preference fk asthe ung prcerence fe woul! be your
‘me
‘ou can et the preferences i either the along ways:
2 Creating the ex fen he res fer
Setting the preferences inthe cose
it uv creste 9 simple Android appicaon. Shar edPrete=~ im whih dhe wae mets provide the login
‘Sinn such a ener name ard patreord’Onve the scr ener thse tah the th data bing maintain
SER Naa the application closed The data would beste perstteity ming the Shaveatsete ence
Gets hestorm the tllowing eps to develop and exeate the She esPre amo appa
c the sSharedPrefDensAndmid application wing Elipae under he
mee areapret dene package
1 Replace the cae ofthe aoc mana ila an the fesayout er withthe code shown on
ing. Dospan the Code othe wt Filet the Snares vefons Appian
fat jveLayout tans:andro\ = nctp://schenas.andro'd.con/agh/re8/andro
hlassteotse*nttp:s7schenas_androtg-con tools"
Sharia ayout-mtathernaceh parent
Sarva Tayout heights natoparen
EON paroid: 1d="Peid unas”
ASyout deh F411 _parent™
[avoucatignrarenteteestrvey
1avout-beloee*Bena/textviens™
ene 10"
Stout Type textrassword”/>
Sten droid: ida"BeSd/textyien2”
ES SUG ae
Saat terrae ae
Ronee
Weitere
IU eat
Romie
\erensaytentvient”
idyoue atetnest eT _parent™
{ayant he lghaseraacontent
Tayout-atignbarencsett=" true
1afevt-belone aera’ texeview?
ayautcaargvntoo=" 89
Srarond:tente"Vaer Name: />
protected vote onsto0(){
Super onstop0)
sharereteances seas» ysnareareterncs ner sceclaring the retrievetaployees() method to retrieve the details OF an employee
eli Srv ereetasloeeing 18) howe sexe
?
ns. comaceO
& ‘database.query(true, tablename, new string () {Empid, Empnane,
ser Seas gee eae nN, eat, mae
gree as
ccnoetoFirstO
d
Jeri eee sett let be ea fo eae
‘public tootean deleteemployeetTong 16)
?
#44, mut) > 0:
Peturn davabase.delete(eablename, Enid +
3
Hyoeclaring the updatetnployee() method to update the details of an Employee
public bootean updateemployeeClong 14, String enpnane, int enpsal)
t
his comectO;
Coneentvalues values = new contentvalues()
values. put emphane, emp
‘calves put epsal,empsal):
‘return database: update(ablenane, cvalues, Eapid + "=" + 44, Tl) >
)
i
In Listing 69, the queries for inserting, updating, deleting, and retrieving the records have been dein we
the appropriate methods. Moreover you can also find the query to crete the Employee table whichis welt
_maintain the employee records forthe EnpioyeeDatabaseArp application.
et us now create the Mainactivity elas from where the appropriate activity class would be inv
perform the database operation
Creating the Layout and Main Activity Class
When you ceate the EeployeebatabaseXep application, the Mainactivi ty dass would have bem cst
wth the activity nail file by default. The Maisdctvity clas ls the mare clos when waa
invoked during the execution ofthe application. Perform ng steps to ney paint
file andthe Hat aAct vit clos encanta noes
1. Openthe atvity mainamt fle loadin the frelayoat folder :
2. Replace the code of the ati tyeat folder ofthe application.
main fle with the code shown in Listing 6.10
Gade of the activity main.oml File of the smployeeDatsbor
snare": //ehoas. :
setName com/ek/rex/adrtaroperations, For exan
the Baployee table
Replace | the code ofthe ~—‘MainActivity. java
‘eckconVkopenVandroldfemployeedatabaseapp folder, with the code shown in Listing 841
android: layout widthe'match_parent™
android: Yayout_height-"match- parent”
tools conten
android: Tayout_aligntight="B+id/updateenp”
android:text-"Add an Eeployee/>
android: \dn"@+id/deecetmp*
androia:layout_width='match parent”
android: Tayout_height="wrap-content”
android: layout_al gnParentiefte"true”
android: layout al gnkight="8+4d/updateeap*
android: layout_below="te\d/updateeap”
‘android: Tayout_aarginrop~" 3069"
android:text="Delete an Exployee” />
‘android: \da0s\6/seectemp™
androva:layout_width="aran_content™
android: Tayout_height="wrap_content™
android: layout al gnrarentiefta"true”
“android: Tayout_alignnight="erid/deletetmp"
Tayout_beTowe"8+ta/selecetep"
Tayout-marginvopa" 2360"
:texte"Get an Employee” />
ide"0vid/selectal emp"
Tayout_widthe"wrap content
Tayout_height="wrap content”
Tayout_alignrarent afte true
Tayout=al gntight="Bria/selectemp"
Tayout_belone"8ssd/selectenp"
ayout_margintop=" 303"
android:texts"cet AIT Employees” />
| Using 610, various buttons have been created for allowing a user to perform diferent database
ple, the Add an Employee button has been created add the details ofan employee in
fil, located inthe1 y Class inthe En
emmy
fing the Code of the ah oyOeDatabasehpe Appiey
Listing: Dpaving the Coo ease te
achage com Koger. and :
Inport anova app acti8y:
ror andra
Viport anrota.os.nndie:
Bore dtdroteven-vien.ontichuistene
Yaport androte widget button;
ric class wainactivity extends Activity Amplements onclickLtstener
ton add.enp, get ate, getcemo, undate_emp, delete ew
PE Thed ane the activity 15 First created *7
MeFi sbidoncreate(eune savedrnstancestate) {
_ state);
‘od.enp. stone] kt istener (nts)
Getcal lien = (avtton) Finaviensyr4(R. 16. seTectaT TER;
Getaallaanp.setOnc] ek stener (his);
Getaenp = (auton) FindviewsyI9(R. 1d. seectenp);
Setaenp. getonc] xt stener (this);
orp = (Button) Findviewsyd(R. 44. updateenp)
erp-setoncVektistener(Ehis)
cecewp = (Button) FindViewdyTG(R. fd. deleteenp);
Gelere_enp.setonc ick fstener (his)
)
public votd onclick(view v) {
fle on Finavon).
‘
aeo))
Intent 4 = new intent(this, Addemployee.class);
starwctintyGt
Fm Findvieny rdf. setectnp))
ntent 4 = new tntentthis, Getemployee.class);
startactivity(i}t
)
fF 6 = Fnavenyaec
updatetmp))
intent 4 = new tntent(this, Updatetmployee.class); 8
startkctinityeiyy es .
)
{6 67 Finavon. deteaeap))
Intent § = new Intent(this, oeTeteenpTo
Fee acne REAMECMS. Deteteemloyee clasStormy e Dem Persemnty
re vert hs fe fot the thon gr i th
Ge appropriate atety cla eld te wate
~ them the sarap
syong the Layout and Activity for the Insert Operation
nthe employee in the Edit Tent views. We would cst he easeup ever yea scent
w ated nthe database. Moneover, we would crate the nsdlop ores ete dnc trance tet
method ofthe Emp loyeetBHelper databese helper cam Prkerm te talortog syste
ier operation
‘rir NIL file eden Loy 2 im the fesflayot fader inthe tn yeas avery
ing 12 shows the code ofthe aiempseyee-ner he
using #12 Displaying the Code ofthe addenp ioyee.xa1 Fle inthe Eng ioyeetat
se) versione"1.0° encadingetutt-6"P>
"ea" ayout mins: androtde httD://schamas.andro\d.con/aph/res/androtd”
narovd: layout-mtdthe"aateh parent”
naroid:Tavout_hetght"match-parent™
tnarois-orventations vertical»
senyp Appicetion
text="Enter the kame of the Employee:” />
‘droid: $4a"8o4/empnane™
Sndroid:layout_widthe"f111_parene™
fndrove:Tayout_heighta'wrap.content™ />
apr ae eer
eet mee
Se Te ogtere:
\de"Beid/emosal” x
layout widehe"FiT1_parent™
layout hei ght="wrap_content™ />
swe
'n Lasting 612, the layout containing two E:¢Tex¢ views, two TextYViews, and a Bu!
degreoo -
—
Ose 1 tw fon dem, mnet in the fe bd ot
ea taqontcndresc.euplayoed Pe “tng ST ee Ta
Using 1. plein the Cn Cane ecianstes nea’
(peckage com hogent android employeesatanasease
Teer rotors vi
Naport aneroié wiaget button:
\Siert tnerove riage tateven
atic void oncreate(aundie savedinstancestate) (
Sinan oncrestesavedinatancestate)
ercontentv iene ayout-addenp oye):
‘Final toloyecopeeiper enpdobelper = new tmployeeoenelger (his)
tonane,” (Cayetent) Findv Vendy 160818: enpnane) $
Tema = ceanevene) fyndvienty16C810-eaps41);
sSE Se © Calton inaviewy (0 a. a)
S055. etncl chat atenerinew View One ckstenerO
‘ ‘
feoverrie
pubtic wate onclickty
wt
et
Seng nae:
name = engnane. getText() toString:
SETS" eeeger parser Comsat. gettext -tostringO)):
eng id= eopdthelper.naerteapheyee(nane, 1):
oust maketentgetnanecontext(), "Your record has been saved successfully with 7+
Toast. LING LON) show
p
eatch(taception ©)
‘
,
evprinestacrraceO:
d
Db
)
} z
In Listing 13, the valves entered by the user inthe 24:2 7ex¢ views have been retrieved ac pase Wi
ser téapioyee() method of the database helper class This method returrs the lng type value
ule generated employee id which has been diaplayed wing the Tost notification,
Slr he mer operation et nw cee he aot ad activity ass ove the eta |
employee i
Creating the Layout and Activity to Search a Record
Similar wo other databases, you can also search a pectic eon rom the S01 ve databse. Imagine you me
‘view the details of an employee whose id i 1. In such a case, you first the erplonee
th ae who det edo fe rom he dase, Pres you no egy te daa
‘st ofthe user data fmplaye i) Lt create he yout that would fe dnlayed oe wer © =
250we would be costing the ety cam aw
‘old be woke ich Oe ren:
cng steps 8 Tea the layout and actin
ron XML fle. got employee
the v9 am, nthe
mg 1 show the code he yoann arene he en
0740.4 Fle then yeaa
‘ndrotoe nt
yout aminssandrot geht: /schenas,
Starete: layout atthe" aatchaparent sn are: /A0h/res/ andres
‘Soret Tavout_hetohtermateh parent”
Moroid-ortentation:"vereleai™ »
1de"@etd/empis™
Tayout width=" f111_garene™
android: Tayout_heighte"wrapecontent™ /»
In sting 14, the Text vi
trom the ser,
1 EaLeText, and 8
_
— earny te Date Cor wemty
seach rn toe the databane
Crete a new Java clas, named GetBmployee, in the fare folder and under the
kogent.android.esployeedatabaseapp package Listing 615 shows the code of the
inp loyee java file
Lining 618 Displaying the Code ofthe Get Emp Loyee. java File inthe Emp Lovee!
achage con. hogent andro, employeedatabaseapp:
‘mort android. widget Toast:
palic class cetmploye extends Activity
button Find.ewp;
aicrext empid;
override
Public void oncreate(aundle savedinstancestate) (
super oncreate(savedinstancestate)
Setcontentview(R. layout getemployee):
final Employeeobve per enpab = new Employeedene}per(h8):
(emohd » (Edi tTent) Findviewty i014. ene}
Jekpp Applicationrapt 6
find emp = (Button) Findviewsyi6¢n.td.0en Find): i
‘ind.enp.setonclickListener (ew View, onclick istener >
‘
‘override
public void onclicktview v)
t
ne enpid = ineger-parserm Cop's. getTextO)-t08tr5ngO);
Cursor ¢ = capdberetrneveenployee (em 10):
Steemoverorerst0)
£ :
Teastaphereneigenasecontet, emploves 14s c-getsring(o «
Tee tapos tans’ hsecpeestringc) t.27, employee salary!
getserageabe oases ericLOR) show?
}
ae
t
yoastnakerextgecaasecontextO,. "No Employee Record
PODS TASLSE RGR LN Shoe:
)
3
In Lnting 615, the cot eievetmpicyee () method of the EnployeedHe} per lat hasbeen inv wg
‘would return the cuss type vai. Further the cursor has bee trated sing the noveTOP «2° meee
tn the record feted from the datatuse would be displayed asthe Toast motication othe wer
[Apart fom setrievng 3 single record from the database, you can alo fetch all records from the Satie
«tase Let ws rat the actiy claw to retrieve all emplayee recor
Creating the Activity Class to Fetch All Records
In the Exployeeteteiper clin, we have created the retrieveAl Employees () method i fecha
employe records rom the uble The Pp loyeeDat abasekep appiation displays all he record evedaie
tification the ser. AS no User input is required chal
records fom the databse, you wou be creting onl the activity clas Get RL Enp! = yes
Perform the following steps create the Set ALEnpLoyees activ ls:
1 Cre a ew ava class, named cevAlitepioyees, in the fe fokler and une te
m-kogentvandroid.erployeedatabaseapp package, Listing 616 shows the cole of te
‘tALlimployees. java fl:
Listing 6.16 Doplaying the Code of the Got ALLEepoyees
Applicaton
‘achage con,hogent.androie.employeedatabaseapp:
File in the Exployeedatabaseiy
‘import android. widget. Toasts
public class cetaT employees extends Activity
‘
override
Public void oncreate(Gundle savedinstancestate) {
super oncreate(savedtnstancestate),
FS caer
SENi fCe.moverorirse()
a
st makeTent
“
android: layout widehe"fi11_parent™
android: layout height=wrap_content™ />
ctexview
android: layout width="wrap_content™
Android: Tayout_nevght=wrap_content
android: text="tmployee Name />
cight="wrap-content™
fandrota:texts"Eaployee Salacy” >
‘androtdsidn"@via/ben update”
i: avout nttho"wrap-content”_
Sndrotd:Tayout_height="wrap content
Android: texe-"upaate” >
andro: ie8S6/emp
Sndroid: layout athe" (11 parent”
[ndrotd:Tayout-height=wrap. content” />
Sarottde "Bin. delate™
{droid Tayout nidtharape content”
{narote! layout eight="orapccontent”
anarotgiteres‘beleve taplayee™ />
“/tineartayeut:
lo Listing 618 the Zoxt View Et Text, and Sutton views have been crate. The we ae
Seletetmployee Bulton clicked, the dts oat
the id the £3: Tex view, ad when i
‘would be delete rom the database
‘operation. Add the coe shown in Listing 620 inthe Se et cEap cys save He
Listing $20: Doplaying the Cale of the ceietetnployee. java Ale tn the Eapioyeet
Applicaton
Package con Aogentandroid.ewployeedatabaseape;
moore android. app. activity
‘nport ano! oT
‘port android: viewsvi
Ie Seid ir
moort androié niet
Inport dnarote.wiaget. rast
odlic class eleteemploee extends Activity
Soret
Bae
Tai mere mane (
order ce
einctanraetaaasl
‘ral eat ee ampere:
Cr angen
es aie ema
inthe tena aeai
‘override
Baile entickvin y ¢
in end Inter ara
‘tila deetenpoyc tas
SSE Tene Sees atest
Toast nherexecge m0,“ mot exit
Ecteanansigetasacorent, -racord dons not exis",
Fos
ne
Crete the | Detetetrployee class inthe fare folder and und
wom-Aogent -android.enployeedatabaseapp package, as the actly 1 lniplemess te af‘Stormy he Data Persatany
tatnung 038 the 1 metho a oe
sare boing display the nee
‘the Database Operations
You ca exe the Bap oye ‘1
scabeseane apiaton by sli the) As Pan
ceptor. hich appear during the igh stekl eappcation ne Sw" APPA Ap
Now tat fete eating the appt, ea eet hy tae
wn file,
cee
{adr \d:anes"empoyeeooneper®
SrdroidTabe\="employeeooel per” >
s/activitye
ey
aharotd:nane<"Getal employees”
Srarotd:Tabeleseet ANT
sactivinye
cactieiey
{andr0\d:nane="updatetmployee"
fnarotd:label="Dpdate tmploves
layout width=
“android: layout_height="wrap_content™
id:gravitye"center™
; ipaddings"104ip" />
—— __Soring the Data Persitonty
ese/naces
fdrota: layer siete
padinge tahoe
std
override
public etd onclick(view ¥)
Tentvien tentview =
String titles WA
Cong” stare = 0
Seiten (o-gettd0) (
Geet Aa ome seo)
4 Clears. $3
cbeeview) Findviety266t 1.58008):me
Cevcarsor sonst)
ut rage maa
‘orore
‘ rere(estie « * on * + dateformat.format(stare) +7 at *
S"Uimaporaat format starts
a
The cursce cassis wed in Listing 622 for tiggering database events
4 Reqs for he read permusin inthe Andro system calendar nthe Andcoian fess
fatowing code suppetchows the reurt forthe read permission:
‘ises-pernission androvdsnans" andro}. perst ton READ-CALEXOAR/>
5. The catendecdenc application now complete Let us execute the application. Before te
remember that your AVD shoul are at APtlevel Mf not do configure accordingly. When you ene
{teapot it wil appee ay shown Fgae 18
0 fle
‘Figure 6.1: Displaying the Interaceof Calendar Application
‘Since no event is ade, the calendar shows the dfailt UNIX date and time in Figure 6.18 By adding ven
the calendar, we can navigate backward and frward in betwen the evens, However, you hive to weak fot
‘email addrens add the evert with the calendar
Creating User-Defined Content Provider
‘You can also create your own content providers in Android. For this, you have to extend a clas fr
Content Provider hase class and overtide the various methods defined in it Les create a”
pplication named Userbe inedContent Provider by performing the following steps
1. Cine the Userbetinedcontenteroviser Android aplication in the Eelipse IDE ankle
com hogert android. veerdatinedconcentprov es prkage
2. Add a new Java class named Contentprovider.java, in the fare folder under ®
‘com, kogent .android.userdefinedcontentprovider package ar shownis ising 62%SS Storing te Data Persistenty
624 Displving the Code ok thy
ter.java Fle inthe
cium ce apenas
(Bist Si ear
ie ad i mae
ert androtd. database cease?
a ae
EES een,
uolic class Contentprovider excends contentrrovider
static final string PROVIDER Ne «
vines
on kogent androv du contentprovidercontentprovider";
static Finai string URt = "concent 7) rope contents oy ders
coarser
SESE ART STOR sane seg ee
aia
root
See
ew UrinatcherCurinatcher.Wo_MATEH);
\4QURI (PROVIDER MANE, Cte
1400 (PROVIDER NAME,
>
coverride
public Int detetecuri uri, String selection, string() seTectionargs) (
switch (uriMatcher.match(uri)) {
ease uricode:
break
defautes
‘throw new XTTegaTargunentexception("unknown URI * ¢ uri
deleteCTARLe Ne, selection, selectionsrgs);
dercontent.oetconenttesolver().notfychangeors, nD:
i :
moc st curt ur
Ne String gectypeCurt ur
NC CEN Coriuatener-eaeenCurt)) {
eine teicoge
return “wnd,androts.cursor.éir/cte'
fate ;
° ‘throw new I) TegalArgumentéxception("Unsupported RI
+ urtds
>
toverride fa
Pes snaert Curt
Tong reas db. insert (TABLE_NAME,,
Te ron det w contenturss.withagpendedté(cOnTeNT-unt, rom
erteabroreopecamtentneotverC sn fychanoe arty mt):
onentvauns yaian))
throm men saLexception( "Failed to add a record
nto" + wrt)
y
Soverride
Public boolean oncreateO) {
Context content = getcontext 0: )
Databasenelper done per = nex catabasewel per (context)
‘db = dowel per. getwr itableoatabase() ;
Af (ao te maliy
)
return false;
eoverrige
public Cursor query(urt uri, stringl) projection, string selection,
String(] selectionargs, string sortorder) {
saLitequeryaur der qb = new SaLitequeryBuilderO;
ab. setTables (TABLE MAM
switch (urimatcher match(uri)) £
ease unicode
‘b-setProjectiontap(values):
‘throw new iTegalargueentéxceptionCUnknown URE + uri);
rE
}
4 (ortorder == nul? || sortorder ==
‘sortorder = mane
Eursor c= ab.qvery(sb, projection, selection, selectionargs, null
‘null, sortorder):
«.setnotiFicationuri(geecontext().getcontentkesolverQ, uri;
return ¢;
4;
doverrige
PUbTHc Ine update(uri uri, Contentvalues values, String selection,
String(] selectiontrgs) {
ine count = 03
switch (urimatcher.match(uri)) (
case uricode’
count ~ db.updateCTABLE NAME, values, selection, selectionsrgs):
break:
sefaute:
‘throw new 11legalArgunentexception(*unknown URE" + uri):
Jercontert 0 .getcontenttesolver().norifychange(urk, nal);
>
private saLiteoatabase db;
Static final string OATABASE MAKE « aya";
State final String TABLEMARE "hanes"
Static Final $nt OATABASE_VersiON = I
Static Final String CREATE OB-TABLE =" CREATE TABLE" + TABLE nau
ose IWTEGER PRIDARY HCY AUTOINGRENENT, =
J ame TEXT NOT NULL) "5
private static class Databasevelper extends sqLiteopenielper {
‘atabasenelper(Context context) {
super (context, DATABASE NAME, mull, OATABASE VERSION):
dLscing 624 Displaying the Code of the
Lunting 625: Displaying the Code ofthe
Appinaon
gp ___ serge rere
errs,
Te Wate enrestescti
PS RRR ee w «
override
BN veld ompprade sa
“ecetSr Sa tsoaabase sot cteversion, int newersion) {
SCO Ee 2 lee,
20+ cd ends the costentiovises ds and overs th ats
ee method eae te wet peo he dara the pen ih The
Seite = ced when the provider sare The on) etd wes & reget om
Sct The inser) method inst rd ine ote
eta ht ec a ening mer ee eed pie ese
Replace code of he Se5098.01 fle lca in the feyalans fle, with the code shown in
ings.anl Fle in the Useroet inedContent Provider
“Caml verstone"1.0° encadinge ath
string sanes"app_nane"suseroetinedcontentProvider\n
gneroid:avthorsties=\"con.hogent, andre. usersef nadcontentprovider.contentprovider\">\al
iprovigerne/stringe
‘string aanew" act On settings"osettingse/string>
‘String nanes"hellonnorla-yael io worid/string.
In isting #24, android authority configured to creat a user defined content provide.
Replace the code ofthe activity man. fle, locate i the /re/layout oer, withthe code shown
Lasting 625
tivity mano Fle inthe Uservet ine acontent eo
“
Sereviee
nel g:ayovt debe F101 parent”
Sra gheeraraa concent”
Soroia:teres kam >
site
Sarotd laant athe paren
Srotd lant neta
Snare layoutetghen"erap-content” />
autor
android: "Goh d/bea”
Sereie: ape pein saree
Sraroid: layout pet gh wrap content”
Srarolg:oncicke ore] ioasouame™
Srarotg:text-"Aad name” />
ln Lntng 25 a linear layout view rete with an 1 ¢Text anda Button controls.raptor 6
ava fle, faceted
S. Replace the code ofthe 3
1 with the code shown in
err\cewn\ kogent\sndrokd\userdefinedcontentprovider foe, with :
Reptegehenaahepah ava File in the User Def ined:
Listing 62% Dreplaying the Coe of the
Application
‘package com, Kogent .androtd.userdefinedcontentprovider
import androtd.os.sundle:
Ymport android. app. Activity:
Ymport andretd.vew.menu:
Yport andres d. content contentvalves
Ymport android. net Ut
tmeort android.os. Bundle:
Ymoort android. vvew.men;
tmport androtd.view.view
Yaport android. wiaget. Ed: eText
import androtd widget. Toasts
public class aavnactivity extends activity (
leoverrive
protected void oncreate(sundle savedinstancestate) (
“Soper.oncreate savedinstancestate) ;
Setcontentvien(k: layout activi ty-main:
y
override
public boolean oncreateoptionsmenu(Menu menu) {
7 Pintlnce che menu; this adds items to the action bar if it is present.
Geomenornfater®) inFlate(Remenu.main, menu);
Feturn true;
d
public void onclicksddvane view view
Contentvalues values = new contentvalues(;
Watues.putCeontentprovider.nane, ((EditText) FindviewBy1d(R
getiextO. costring0):
uri’url = getcontentResolver() insert (contentprovider ,cONTENT.URT. vals):
Toast makeYext(getoaseContext(), "New record inserted”, Toast.Ui
-oxenane))
“Show!
,
>
Ie Listing 626, the tainactiviy das is created. The onc1ckAdatane () method is wed wa”
ected
46 Addithe provider clement in the Anson fest -xmt il, as shown in the following soe si
‘ane tcation
1Toweackupe"true"
‘cone*adravable/c_Tauncher™
Sndrova!tabel-sestring/app_nane*
fndro\a:these-"Bstyle/apprhene” >
ctetivity
tndr¥id:nanes"con,kogent. Dlackbook,userdetinedcontentprovidersai
Sneha Tape siring/app_nane™=5 wTeTonFieseonsen
‘
ivi
etvier
sal Fle in the
omeCoH en ey
"Be id/res” :
Tayout-width="natch parent™,
‘Tayout_hetght=arap_content
android: ayout_narginveFt=" i065"
android:cTreuables false"
androtdiense" 10" >