Книга: Beginning Android

Start at the Beginning

Start at the Beginning

No databases are automatically supplied to you by Android. If you want to use SQLite, you have to create your own database, then populate it with your own tables, indexes, and data.

To create and open a database, your best option is to craft a subclass of SQLiteOpenHelper. This class wraps up the logic to create and upgrade a database, per your specifications, as needed by your application. Your subclass of SQLiteOpenHelper will need three methods:

• The constructor, chaining upward to the SQLiteOpenHelper constructor. This takes the Context (e.g., an Activity), the name of the database, an optional cursor factory (typically, just pass null), and an integer representing the version of the database schema you are using.

• onCreate(), which passes you a SQLiteDatabase object that you need to populate with tables and initial data, as appropriate.

onUpgrade(), which passes you a SQLiteDatabase object and the old and new version numbers, so you can figure out how best to convert the database from the old schema to the new one. The simplest, albeit least friendly, approach is to simply drop the old tables and create new ones. This is covered in greater detail in Chapter 28.

The rest of this chapter will discuss how you actually create tables, insert data, drop tables, etc., and will show sample code from a SQLiteOpenHelper subclass.

To use your SQLiteOpenHelper subclass, create an instance and ask it to getReadableDatabase() or getWriteableDatabase(), depending upon whether or not you will be changing its contents:

db = (new DatabaseHelper(getContext())).getWritableDatabase();
return (db == null) ? false : true;

This will return a SQLiteDatabase instance, which you can then use to query the database or modify its data.

When you are done with the database (e.g., your activity is being closed), simply call close() on the SQLiteDatabase to release your connection.

Оглавление книги

Генерация: 0.917. Запросов К БД/Cache: 3 / 0
Вверх Вниз