今天看《第一行代碼--Android》,有一個地方沒看懂,創建一個名為bookstore.db的數據庫,
這個數據庫在哪裡創建,也就是創建數據庫的代碼在哪裡寫?
SQLiteOpenHelper類的構造方法中傳入db名稱自然就會創建數據庫了,然後在SQLiteOpenHelper.onCreate()方法裡創建表。
// A string that defines the SQL statement for creating a table
private static final String SQL_CREATE_MAIN = "CREATE TABLE " +
"main " + // Table's name
"(" + // The columns in the table
" _ID INTEGER PRIMARY KEY, " +
" WORD TEXT"
" FREQUENCY INTEGER " +
" LOCALE TEXT )";
...
/**
* Helper class that actually creates and manages the provider's underlying data repository.
*/
protected static final class MainDatabaseHelper extends SQLiteOpenHelper {
/*
* Instantiates an open helper for the provider's SQLite data repository
* Do not do database creation and upgrade here.
*/
MainDatabaseHelper(Context context) {
super(context, DBNAME, null, 1);
}
/*
* Creates the data repository. This is called when the provider attempts to open the
* repository and SQLite reports that it doesn't exist.
*/
public void onCreate(SQLiteDatabase db) {
// Creates the main table
db.execSQL(SQL_CREATE_MAIN);
}
}
更詳細的可以查看google developer官方說明:http://developer.android.com/guide/topics/providers/content-provider-creating.html