Use SQLiteAssetHelper
。您添加一個庫,創建一個SQLiteAssetHelper
(而不是正常的SQLiteOpenHelper
)的子類,並將您的數據庫置於assets/
。
因此,例如,在this sample app,我添加庫中app/build.gradle
:
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1'
我DatabaseHelper
延伸SQLiteAssetHelper
:
/***
Copyright (c) 2008-2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.dbasset;
import android.content.Context;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
class DatabaseHelper extends SQLiteAssetHelper {
static final String TITLE="title";
static final String VALUE="value";
static final String TABLE="constants";
private static final String DATABASE_NAME="constants.db";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
}
而且我的數據庫is in app/src/main/assets/databases/
。
一切從有別的就像在Android中正常使用的SQLite。第一次運行應用程序時,數據庫會自動從資產中解壓縮。
嗯,這工作得很好。猜猜我應該多看看盒子外面。快速說明問題,因爲我對Android有點新,在下載並解壓縮之後,我會在哪裏放置SQLiteAssetHelper文件? – Jacob
@Jacob:「在下載並解壓縮SQLiteAssetHelper文件後,我應該在哪裏放置它?」 - 我不知道你的意思。 SQLiteAssetHelper是Java類,來自庫。假設您使用的是Android Studio,將庫添加到模塊的'build.gradle'文件中。如果你下載了'SQLiteAssetHelper'的GitHub倉庫,你可以做到這一點,這是不必要的,除非你分叉圖書館。 – CommonsWare
哦。咄。沒關係,我生病了,因此腦殘。 – Jacob