TShopping

標題: Using your own SQLite database in Android applications [打印本頁]

作者: woff    時間: 2013-10-11 12:49
標題: 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:
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

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:
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.

         This article has also been translated into Serbo-Croatian by Anja Skrba from Webhostinggeeks.com.

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





歡迎光臨 TShopping (http://www.tshopping.com.tw/) Powered by Discuz! X3.2