Chapter 11. Data Persistence

11.1. Introduction: Data Persistence

Ian Darwin

Discussion

Data persistence is a wide topic. In this chapter we focus on selected topics, including:

  • Filesystem topics relating to the app-accessible parts of the filesystems (/sdcard and friends)—but we assume you know the basics of reading/writing text files

  • Persisting data in a database, commonly but not exclusively SQLite.

  • More specifically, reading and writing the Contacts database

  • Some data format conversions (e.g., JSON and XML conversions) that don’t fit naturally into any of the other chapters

11.2. Getting File Information

Ian Darwin

Problem

You need to know all you can about a given file “on disk,” typically on internal memory or on the SD card.

Solution

Use a java.io.File object.

Discussion

The File class has a number of “informational” methods. To use any of these, you must construct a File object containing the name of the file on which it is to operate. It should be noted up front that creating a File object has no effect on the permanent filesystem; it is only an object in Java’s memory. You must call methods on the File object in order to change the filesystem; as we’ll see, there are numerous “change” methods, such as one for creating a new (but empty) file, one for renaming a file, and so on, as well as many informational methods. Table 11-1 lists some of the informational methods.

Table 11-1. File class informational methods
Return typeMethod nameMeaning
booleanexists()True if something of that name exists ...

Get Android Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.