8 - 2 - Data Management- Partaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2 (13-43)

6
Hi, I'm Adam Porter, and this is Programming Mobile Applications for Android Handheld Systems. As I said before, Android also allows applications to write to external memory. One extra twist that you'll need to consider however, when you do this, is that external memory can be removable. For example, when it's provided by an SD card. And because of this, that media can appear or disappear without warning. And therefore, when your application is going to write to external memory, you'll first need to determine the state of the external memory. Now one way to do that is by using the environment class's getExternalStorageState Method. That method will return a value indicating the current state of the device's external memory. And some of those values are shown here, for example, there's MEDIA_MOUNTED, which means that the media is present and that it's mounted with read and write access. There's MEDIA_MOUNTED_READ_ONLY, which means that the media is present and mounted, but as read-only access. And there's MEDIA_REMOVED, which indicates that the external memory is not present. And of course, there's several other values as well. If your application wishes to write to external memory, Then it will need to request the appropriate permission. Specifically, you'll need to add the WRITE_EXTERNAL_STORAGE permission, in the application's AndroidManifest.xml file. Our next example application is called DataManagement FileExternalMemory. This application reads an image file from the res/raw directory. It copies that file to external storage, it reads the image data back from that external file, and then it displays the image on the screen. Let's take a look at that application right now. So here's my device. When I start the Data Management File External Memory application, you'll see an image displayed on the screen. Here it goes.

description

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Transcript of 8 - 2 - Data Management- Partaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2 (13-43)

Page 1: 8 - 2 - Data Management- Partaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2 (13-43)

Hi, I'm Adam Porter, and this isProgramming Mobile Applications forAndroid Handheld Systems.As I said before, Android also allowsapplications to write to external memory.One extra twist that you'll need toconsider however, whenyou do this, is that external memory canbe removable.For example, when it's provided by an SDcard.And because of this, that media can appearor disappear without warning.And therefore, when your application isgoing to write to externalmemory, you'll first need to determine thestate of the external memory.Now one way to do that isby using the environment class'sgetExternalStorageState Method.That method will return a value indicatingthe current state of the device's externalmemory.And some of those values are shown here,for example, there's MEDIA_MOUNTED, whichmeans that the media is present and thatit's mounted with read and write access.There's MEDIA_MOUNTED_READ_ONLY, whichmeans thatthe media is present and mounted, but asread-only access.And there's MEDIA_REMOVED, which indicatesthat the external memory is not present.And of course, there's several othervalues as well.If your application wishes to write toexternal memory,Then it will need to request theappropriate permission.Specifically, you'll need to add theWRITE_EXTERNAL_STORAGEpermission, in the application'sAndroidManifest.xml file.Our next example application is calledDataManagement FileExternalMemory.This application reads an image file fromthe res/raw directory.It copies that file to external storage,it reads the image data backfrom that external file, and then itdisplays the image on the screen.Let's take a look at that applicationright now.Sohere's my device.When I start the Data Management FileExternal Memoryapplication, you'll see an image displayedon the screen.Here it goes.

Page 2: 8 - 2 - Data Management- Partaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2 (13-43)

Let'slook at the source code, to betterunderstand where this image data camefrom.Sohere's the application open in the IDE.Now, I'll open the main activity.In the onCreate method, the code checksthe external storage stateto ensure that the media is mounted, andthat is readable and writable.After that, the code gets the externalfile directory, where pictures arenormally stored.And it constructs a new file object,pointing within that directory.Next, it checks whether a file actuallyexists on the external memory.The code then calls the copy image data tomemory method.Let's look at that method.Now this method starts by creating a newoutput stream, thatwill be used to write to a file, on theexternal memory.Next, it creates an input stream, so thatit can read image data from the res/rawdirectory.And finally, it copies the data from theinput stream to the output stream.When this method completes, there will bea new file in external memory.Now, going back to the on create method,the code gets a reference to an imageview, and insets the image URI to bethe file that was just created in externalmemory.If your application creates temporaryfiles, thenyou may consider writing these to cachedirectories.Cache files are temporary files that maybedeleted by the system, when storage islow.And these files are removed when theapplication is uninstalled.And you can get access to the Cachedirectory, by using the context class's,getCacheDir method.This method returns the absolute path toanapplication-specific directory, that canbe used for temporary files.Alternatively, you can also use thecontext class's getExternalCacheDirmethod, which returnsa file object representing a directory forCache files in external storage.When your application reads and uses

Page 3: 8 - 2 - Data Management- Partaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2 (13-43)

larger amounts of structured andcomplex data, you may want to put thatdata in a database.Android provides an implementation ofSQLite, which allows applications tocreate and use in-memory relationaldatabases.SQLite is designed to operate within averysmall footprint, say less than 300kilobites of storage.SQLIte is however, a full fledgedrelational database.It implements most of the SQL92 standard,and it supports highly reliableACID transitions, which means that it'stransactions are atomic, consistent,isolated, and durable.To use an SQL database in yourapplications, Androidrecommends that you use a helper classcalled SQLiteOpenHelper.And what you'll do, is you'll create asubclass of this SQLiteOpenHelper class.And in the constructor for that class,you'll need to call the superclasses constructor, passing in someinformationabout the database you want to create.Next, you'll override the onCreate method,the onUpgrade method as well.Now typically, in onCreate, you'll executeone or moreCreate Table commands, which define thedatabase's structure and layout.And after that, you'll use theSQLiteOpenHelper methods,for example, to open and return theunderlying SQLite database.And then, you execute operations on theunderlying database.Our last example application is calledDataManagementSQL.This application creates an SQLitedatabase, and theninserts several records, some with errors,into the database.The application will also display a buttonlabeled Fix.And when the user presses the Fix button,the application willdelete and update, some of those recordsthat were just inserted.And it will then re-display the updateddatabase records on the screen.Let's take a look at that application now.Sohere is my device.And now, I'll start up the Data ManagementSQL application.

Page 4: 8 - 2 - Data Management- Partaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2 (13-43)

As you can see, the application nowdisplays four database records,each containing a record ID, and the nameof an artist.At the bottom of the screen, there's alsothe Fix button that I mentioned earlier.When I press this button, record numbertwo, Lady Gaga, will be deleted.And record number three, Johnny Cash, willbeupdated to correctly spell the artist'sfirst name.Let me hit the Fix button now.And as you can see, record number two hasbeen deleted, andrecord number three now shows the correctspelling of Johnny Cash's first name.Let's look at the source code for thisapplication.Here's the application open in the IDE.I'll now open up the main activity.Here in the onCreate method, webegin by creating a new DatabaseOpenHelperinstance.And that class is a subclass ofSQLiteOpenHelper.Let'stake a look at that class.Theconstructor for this class, calls thesuper class's constructor passing ininformation, such as the name of thedatabase, and a version number.Now this class's onCreate method, receivesanSQLite database object, and then calls itsExecSQLmethod, passing in a string, whichcorresponds to an actualSQL command, that will create a tablenamed Artists.And that table will contain two fields, aninteger ID, and a string for the artist'sname.This class also has a DeleteDatabasemethod, which simply deletes the database.Now going back to the main activity, theonCreate method continues by getting areference to the underlying data base,that can be used for reading and writing.Next, it calls the clearAll method, whichjust deletes every record in the database.After that, the code calls theInsertArtist method,which inserts a number of records into thedatabase.Now this method first creates aContentValues object, and then putsinformationinto that object, corresponding in this

Page 5: 8 - 2 - Data Management- Partaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2 (13-43)

case, to the artist's name, Frank Sinatra.Next, it inserts the record into theArtist table by calling the insert method.Now since the ID field is auto generatedbythe database, the application doesn't needto include it here.Next, the code clears out the valuesobject,and then add a second record for LadyGaga.A third record for Johnny Cash, and thefourth record, for Ludwig van Beethoven.Now, going back up to the onCreate method,the code calls the readArtist method,which reads all the records in thedatabase, and returns a cursor object.A cursor is essentially an iterator over aset of records returned by a queryoperation.And this cursor is then used to create anadapter forthe list view, that will display theserecords on the display.And finally, the code sets a listener onthe Fix button.When the user presses this button, thecode calls the Fix method.Let's scroll down to that method.This method first calls the Delete method,which finds therecord with the artist name Lady Gaga, andthen deletes it.And after that, the method creates aContentValuesobject, with the right spelling of thename Johnny.It then performs an update operation, thatfirst finds the recordwith the misspelled name, and thenreplaces it with the correct spelling.You need to debug your databaseapplications, thereare several things you might need to know.First, the database files arestored in the data/data/packagename/databases directory.And you examine these files, by firstopening ashell to the emulator, or to your device,with ADB.For instance, if your emulator's name isemulator-5554, thenyou can issue this command to open ashell.And once the shell is open, you can thenusethe SQLite3 command to open the connectionto the database itself.And from there, you can type, for example,

Page 6: 8 - 2 - Data Management- Partaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2 (13-43)

.help toget more information about the specificcommands this program understands.So that's all for our lesson on DataManagement.Please join me next time, when we'lldiscuss the ContentProvider class.See you then.[BLANK_AUDIO]