日期:2014-05-16  浏览次数:20445 次

使用自己的数据库SQLite database

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

Most all of the Android examples and tutorials out there assume you want to create and populate your database at runtime and not to use and access an independent, preloaded database with your Android application.

The method I'm going to show you takes your own SQLite database file from the "assets" folder and copies into the system database path of your application so the SQLiteDatabase API can open and access it normally.

?

1. Preparing the SQLite database file.

Assuming you already have your sqlite database created, we need to do some modifications to it.
If you don't have a sqlite manager I recommend you to download the opensource SQLite Database Browser available for Win/Linux/Mac.

Open your database and add a new table called "android_metadata", you can execute the following SQL statement to do it:

CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')

Now insert a single row with the text 'en_US' in the "android_metadata" table:

INSERT INTO "android_metadata" VALUES ('en_US')

Then, it is necessary to rename the primary id field of your tables to "_id" so Android will know where to bind the id field of your tables.
You can easily do this with SQLite Database Browser by pressing the edit table button Edit Table, then selecting the table you want to edit and finally selecting the field you want to rename.

After renaming the id field of all your data tables to "_id" and adding the "android_metadata" table, your database it's ready to be used in your Android application.

Modified database

Modified database

Note: in this image we see the tables "Categories" and "Content" with the id field renamed to "_id" and the just added table "android_metadata".

2. Copying, opening and accessing your database in your Android application.

Now just put your database file in the "assets" folder of your project and create a Database Helper class by extending the SQLiteOpenHelper class from the "android.database.sqlite" package.

Make your DataBaseHelper class look like this:

public class DataBaseHelper extends SQLiteOpenHelper{
?
    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
?
    p