TShopping

 找回密碼
 註冊
搜索
查看: 700|回復: 0

[教學] Using your own SQLite database in Android applications

[複製鏈接]
發表於 2013-10-11 12:49:04 | 顯示全部樓層 |閱讀模式
 
Push to Facebook Push to Plurk Push to Twitter 
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:




    1. CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
    複製代碼

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




    1. 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 , 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

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:






    1. public class DataBaseHelper extends SQLiteOpenHelper{

    2.     //The Android's default system path of your application database.
    3.     private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
    4.     private static String DB_NAME = "myDBName";
    5.     private SQLiteDatabase myDataBase;
    6.     private final Context myContext;

    7.     /**
    8.      * Constructor
    9.      * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
    10.      * @param context
    11.      */
    12.     public DataBaseHelper(Context context) {
    13.             super(context, DB_NAME, null, 1);
    14.             this.myContext = context;
    15.     }        

    16.   /**
    17.      * Creates a empty database on the system and rewrites it with your own database.
    18.      * */
    19.     public void createDataBase() throws IOException{
    20.             boolean dbExist = checkDataBase();
    21.             if(dbExist){
    22.                     //do nothing - database already exist
    23.             }else{
    24.                     //By calling this method and empty database will be created into the default system path
    25.                     //of your application so we are gonna be able to overwrite that database with our database.
    26.                     this.getReadableDatabase();

    27.                     try {
    28.                             copyDataBase();
    29.                     } catch (IOException e) {
    30.                             throw new Error("Error copying database");
    31.                     }
    32.             }
    33.     }

    34.     /**
    35.      * Check if the database already exist to avoid re-copying the file each time you open the application.
    36.      * @return true if it exists, false if it doesn't
    37.      */
    38.     private boolean checkDataBase(){
    39.             SQLiteDatabase checkDB = null;
    40.             try{
    41.                     String myPath = DB_PATH + DB_NAME;
    42.                     checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    43.             }catch(SQLiteException e){
    44.                     //database does't exist yet.
    45.             }
    46.             if(checkDB != null){
    47.                     checkDB.close();
    48.             }
    49.             return checkDB != null ? true : false;
    50.     }

    51.     /**
    52.      * Copies your database from your local assets-folder to the just created empty database in the
    53.      * system folder, from where it can be accessed and handled.
    54.      * This is done by transfering bytestream.
    55.      * */
    56.     private void copyDataBase() throws IOException{
    57.             //Open your local db as the input stream
    58.             InputStream myInput = myContext.getAssets().open(DB_NAME);
    59.             // Path to the just created empty db
    60.             String outFileName = DB_PATH + DB_NAME;

    61.             //Open the empty db as the output stream
    62.             OutputStream myOutput = new FileOutputStream(outFileName);

    63.             //transfer bytes from the inputfile to the outputfile
    64.             byte[] buffer = new byte[1024];
    65.             int length;
    66.             while ((length = myInput.read(buffer))>0){
    67.                     myOutput.write(buffer, 0, length);
    68.             }
    69.             //Close the streams
    70.             myOutput.flush();
    71.             myOutput.close();
    72.             myInput.close();
    73.     }

    74.     public void openDataBase() throws SQLException{
    75.             //Open the database
    76.             String myPath = DB_PATH + DB_NAME;
    77.             myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    78.     }

    79.     @Override
    80.     public synchronized void close() {
    81.             if(myDataBase != null)
    82.                     myDataBase.close();
    83.             super.close();
    84.     }

    85.     @Override
    86.     public void onCreate(SQLiteDatabase db) {
    87.     }

    88.     @Override
    89.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    90.     }

    91.     // Add your public helper methods to access and get content from the database.
    92.     // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
    93.     // to you to create adapters for your views.

    複製代碼



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.

        



    1. DataBaseHelper myDbHelper = new DataBaseHelper();
    2.         myDbHelper = new DataBaseHelper(this);

    3.         try {
    4.                 myDbHelper.createDataBase();
    5.         } catch (IOException ioe) {
    6.                 throw new Error("Unable to create database");
    7.         }

    8.         try {
    9.                 myDbHelper.openDataBase();
    10.         }catch(SQLException sqle){
    11.                 throw sqle;
    12.         }
    複製代碼

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/

 

臉書網友討論
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2016-12-11 16:18 , Processed in 0.056957 second(s), 22 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表