Recipe 10.7 Creating and Using SQLite Databases Programmatically

Android versions
Level 1 and above
Permissions
None
Source code to download from Wrox.com
Databases.zip

So far, all the recipes you have seen in this chapter are useful for saving simple sets of data. To save relational data, using a database is much more efficient. For example, to store the results of all the students in a school, it is much more efficient to use a database to represent them because you can use database querying to retrieve the results of specific students. Moreover, using databases enables you to enforce data integrity by specifying the relationships between different sets of data.

Android uses the SQLite database system. The database that you create for an application is only accessible to itself; other applications will not be able to access it.

In this recipe, you will learn how to programmatically create a SQLite database in your Android application. For Android, the SQLite database that you create programmatically in an application is always stored in the /data/data/<package_name>/databases folder.

Solution

A good practice for dealing with databases is to create a helper class to encapsulate all the complexities of accessing the data so that it is transparent to the calling code. Hence, for this recipe, you will create a helper class called DBAdapter (named DBAdapter.java) that creates, opens, closes, and uses a SQLite database.

In this example, you are going to create ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.