Hello, Android

Page 125

A CCESSING THE I NTERNAL F ILE S YSTEM

The onSaveInstanceState( ) method is defined on line 16. We call the superclass to get its state, and then we save ours and theirs in a Bundle. Failing to call the superclass will result in a runtime error. Later, onRestoreInstanceState( ) (line 26) will be called to tease out the information we saved. We get our own x and y positions from the Bundle, and then we call the superclass to let it get whatever it needs. After making these changes, the cursor will be remembered by PuzzleView, just like any other Android view. Next let’s look at keeping data in plain old files.

6.4 Accessing the Internal File System Android runs Linux under the covers, so there’s a real file system mounted in there with a root directory and everything. The files are stored on nonvolatile flash memory built into the device, so they are not lost when the phone is turned off. All of the usual Java file I/O routines from the java.io package are available for your program to use, with the caveat that your process has limited permissions so it can’t mess up any other application’s data. In fact, the main thing it can access is a package private directory created at install time (/data/data/packagename). A few helper methods are provided on the Context class (and thus on the Activity class extended by each of your activities) to let you read and write data there. Here are the ones you’re most likely to need: deleteFile( ) fileList( ) openFileInput( ) openFileOutput( )

Delete a private file. Returns true if it worked, false otherwise. Return a list of all files in the application’s private area in a String array. Open a private file for reading. Returns a java.io.FileInputStream. Open a private file for writing. Returns a java.io.FileOutputStream.

However, since this internal memory is limited, I recommend you keep the size of any data you put there low, say a megabyte or two at the most, and carefully handle I/O errors when writing in case the space runs out. Luckily, internal memory isn’t the only storage that you have to work with. Report erratum

Prepared exclusively for Trieu Nguyen

this copy is (P1.5 printing, July 21, 2009)

125


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.