首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

应用自己的数据库SQLite database

2012-08-21 
使用自己的数据库SQLite databasehttp://www.reigndesign.com/blog/using-your-own-sqlite-database-in-an

使用自己的数据库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:

You can easily do this with SQLite Database Browser by pressing the edit table button 应用自己的数据库SQLite database, 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.

应用自己的数据库SQLite database

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:

That's it.
Now you can create a new instance of this DataBaseHelper class and call the createDataBase() and openDataBase() methods. Remember to change the "YOUR_PACKAGE" to your application package namespace (i.e: com.examplename.myapp) in the DB_PATH string.

       ...?        DataBaseHelper myDbHelper = new DataBaseHelper();        myDbHelper = new DataBaseHelper(this);?        try {?        myDbHelper.createDataBase();? } catch (IOException ioe) {? throw new Error("Unable to create database");? }? try {? myDbHelper.openDataBase();? }catch(SQLException sqle){? throw sqle;? }?        ...

?

Enjoyed this post? ReignDesign is a great team of tech-savvy developers providing RIA and mobile services. For more articles like this, subscribe to our blog feed.

热点排行