如何在 Android 项目中插入现有数据库
How to insert existing DataBase in Android Project
我想将现有的 SQLite 数据库插入到我的 Android 项目中。
换句话说,我不想创建它,只是为了能够在我的应用程序中访问它。
我怎样才能访问数据库,我应该把它放在哪个文件夹中?
您必须将它添加到资产文件夹中并在助手中引用它 class
将您的数据库放入资产文件夹
public void CopyDataBaseFromAsset() throws IOException {
InputStream in = context.getAssets().open(DATABASE_NAME);
Log.e("sample", "Starting copying");
String outputFileName = DATABASE_PATH+DATABASE_NAME;
File databaseFile = new File( "/data/data/*YOUR PACKGE NAME*/databases");
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
OutputStream out = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer))>0){
out.write(buffer,0,length);
}
Log.e("sample", "Completed" );
out.flush();
out.close();
in.close();
}
好吧,这很简单,只要把你的 database.db 放在 assets 文件夹中,你就可以使用 Android SQLiteAssetHelper 来读写数据库,这个库让这个过程变得非常简单和直接。
导入库
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
然后
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "northwind.db";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
这就是访问数据库所需要做的全部工作。
Here 是为方便起见的完整示例。
我想将现有的 SQLite 数据库插入到我的 Android 项目中。
换句话说,我不想创建它,只是为了能够在我的应用程序中访问它。
我怎样才能访问数据库,我应该把它放在哪个文件夹中?
您必须将它添加到资产文件夹中并在助手中引用它 class
将您的数据库放入资产文件夹
public void CopyDataBaseFromAsset() throws IOException {
InputStream in = context.getAssets().open(DATABASE_NAME);
Log.e("sample", "Starting copying");
String outputFileName = DATABASE_PATH+DATABASE_NAME;
File databaseFile = new File( "/data/data/*YOUR PACKGE NAME*/databases");
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
OutputStream out = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer))>0){
out.write(buffer,0,length);
}
Log.e("sample", "Completed" );
out.flush();
out.close();
in.close();
}
好吧,这很简单,只要把你的 database.db 放在 assets 文件夹中,你就可以使用 Android SQLiteAssetHelper 来读写数据库,这个库让这个过程变得非常简单和直接。
导入库
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
然后
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "northwind.db";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
这就是访问数据库所需要做的全部工作。
Here 是为方便起见的完整示例。