100% found this document useful (1 vote)
24 views36 pages

Database Sqlite Unit4

The document discusses various data storage mechanisms available on the Android platform, including Shared Preferences, Internal Storage, External Storage, SQLite Database, and Content Providers. It explains how to use Shared Preferences for storing user configuration details and provides a brief overview of creating and managing an SQLite database for applications that require more complex data management. The document includes code examples and steps to implement these storage options in Android applications.

Uploaded by

m7r3o
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (1 vote)
24 views36 pages

Database Sqlite Unit4

The document discusses various data storage mechanisms available on the Android platform, including Shared Preferences, Internal Storage, External Storage, SQLite Database, and Content Providers. It explains how to use Shared Preferences for storing user configuration details and provides a brief overview of creating and managing an SQLite database for applications that require more complex data management. The document includes code examples and steps to implement these storage options in Android applications.

Uploaded by

m7r3o
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
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 230 ould 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://[Link]'[Link]/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 & ‘[Link](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 [Link](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 [Link] File of the smployeeDatsbor snare": //ehoas. : setName com/ek/rex/adrtar operations, 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 inthe 1 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 [Link]: Bore [Link] Yaport androte widget button; ric class wainactivity extends Activity Amplements onclickLtstener ton [Link], get ate, getcemo, undate_emp, delete ew PE Thed ane the activity 15 First created *7 MeFi sbidoncreate(eune savedrnstancestate) { _ state); ‘[Link]. stone] kt istener (nts) Getcal lien = (avtton) Finaviensyr4(R. 16. seTectaT TER; [Link]] 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, [Link]); starwctintyGt Fm Findvieny rdf. setectnp)) ntent 4 = new tntentthis, [Link]); startactivity(i}t ) fF 6 = Fnavenyaec updatetmp)) intent 4 = new tntent(this, [Link]); 8 startkctinityeiyy es . ) {6 67 Finavon. deteaeap)) Intent § = new Intent(this, oeTeteenpTo Fee acne REAMECMS. Deteteemloyee clas Stormy 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://[Link]\[Link]/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'[Link]™ /> 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! degre oo - — Ose 1 tw fon dem, mnet in the fe bd ot ea [Link] 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= [Link](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 © = 250 we 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 [Link] 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 [Link]; 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 Application rapt 6 find emp = (Button) Findviewsyi6¢[Link].0en Find): i ‘[Link] (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 [Link] package, Listing 616 shows the cole of te ‘tALlimployees. java fl: Listing 6.16 Doplaying the Code of the Got ALLEepoyees Applicaton ‘achage con,[Link]: 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 SEN i [Link]() a st makeTent “ Stertview ‘andro\dTayout witha"wrap content” {ndroid:Tayout_he ight="wrap content” texte"enter the taployee 14° /> 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 [Link]; moore android. app. activity ‘nport ano! oT ‘port android: viewsvi Ie Seid ir moort androié niet Inport [Link]. 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 -[Link] 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 toverride fa Pes snaert Curt Tong reas db. insert (TABLE_NAME,, Te ron det w [Link]é(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= [Link](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 ([Link](uri)) ( case uricode’ count ~ [Link] 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): d Lscing 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 [Link] Fle in the Useroet inedContent Provider “Caml verstone"1.0° encadinge ath string sanes"app_nane"suseroetinedcontentProvider\n gneroid:avthorsties=\"[Link], andre. usersef [Link]\">\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 “<[Link] anas:androu-¥eta/ Seamus andro con/agh/res/anéroi a” Sesrele ayeve-maehe"f] sarert SSrhe: layout hevgnterficparent™ Seroig-ortentation vertical > 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 .[Link] import [Link]: Ymport android. app. Activity: Ymport [Link]: Yport andres d. content contentvalves Ymport android. net Ut tmeort [Link]. Bundle: Ymoort android. [Link]; tmport [Link] Yaport android. wiaget. Ed: eText import androtd widget. Toasts public class aavnactivity extends activity ( leoverrive protected void oncreate(sundle savedinstancestate) ( “[Link] 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([Link], menu); Feturn true; d public void onclicksddvane view view Contentvalues values = new contentvalues(; [Link], ((EditText) FindviewBy1d(R getiextO. costring0): uri’url = getcontentResolver() insert (contentprovider ,[Link]. vals): Toast makeYext(getoaseContext(), "New record inserted”, [Link] -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 ‘Button . androtdside"@eid/oemterrieve” android: ayout_wigthe parent” androids layout-hetght="erap-content™_ androie:oncTicke"onc chop aynanes” androig:texte"Display names” /> 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" >

You might also like