You and the Horse You Rode in On
Let’s suppose you have some static data you want to ship with the application, such as a list of words for a spell‑checker. The easiest way to deploy that is to put the file in the res/raw directory, so it gets put in the Android application APK file as part of the packaging process as a raw resource.
To access this file, you need a object. From an activity, that is as simple as calling . A object offers to get an on the file you specify. Rather than a path, expects an integer identifier for the file as packaged. This works just like accessing widgets via – if you put a file named in , the identifier is accessible in Java as .
Since you can get only an , you have no means of modifying this file. Hence, it is really useful only for static reference data. Moreover, since it is unchanging until the user installs an updated version of your application package, either the reference data has to be valid for the foreseeable future, or you need to provide some means of updating the data. The simplest way to handle that is to use the reference data to bootstrap some other modifiable form of storage (e.g., a database), but this makes for two copies of the data in storage. An alternative is to keep the reference data as is but keep modifications in a file or database, and merge them together when you need a complete picture of the information. For example, if your application ships a file of URLs, you could have a second file that tracks URLs added by the user or reference URLs that were deleted by the user.
In the sample project available in the Source Code section of http://apress.com, you will find a reworking of the listbox example from Chapter 8, this time using a static XML file instead of a hard‑wired array in Java. The layout is the same:
In addition to that XML file, you need an XML file with the words to show in the list:
While this XML structure is not exactly a model of space efficiency, it will suffice for a demo.
The Java code now must read in that XML file, parse out the words, and put them someplace for the list to pick up:
Дата добавления: 2015-05-16; просмотров: 773;