【发布时间】:2014-10-20 13:12:52
【问题描述】:
我想使用 250 兆字节 的预加载 sqlite 数据库。我已将数据库复制到 assets 文件夹中。由于我们不能直接访问资产数据库,我将数据库从资产复制到
“context.getFilesDir()”文件夹。
使用这种策略,我的应用程序适用于高达 5-6 兆字节的小型数据库,但如果我对大型数据库这样做,应用程序会崩溃,这正是我想要的。
我正在尝试做的事情有什么更好的方法或有什么问题吗? 我已经尝试过可能副本的解决方案 Android: Accessing assets folder sqlite database file with .sqlite extension Getting a column from .sqlite containing multiple tables with multiple columns How to use preloaded SQLite database in Android from Assets
我的 SqliteHelper 代码如下供参考。
package com.example.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
/**
* Created by MOHIT on 06-08-2014.
*/
public class SQLiteHelper {
private static final String DB_NAME = "alldb.sqlite";
//private String DB_NAME = "alldb.sqlite";
private Context context;
private SQLiteDatabase database;
public SQLiteHelper(Context context) {
this.context = context;
}
public SQLiteDatabase openDatabase() {
File dbFile = new File(context.getFilesDir(), DB_NAME);
if (!dbFile.exists()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
// Utilities.makeToastLong(context, "Error here");
throw new RuntimeException("Error creating source database", e);
}
}
database= SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
return database;
}
public void closeDatabase()
{
if(database!=null&& database.isOpen())
database.close();
}
private void copyDatabase(File dbFile) throws IOException {
try {
InputStream is = context.getAssets().open(DB_NAME);
dbFile.createNewFile();
OutputStream os = new FileOutputStream(dbFile,false);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}catch (Exception e)
{
Log.e(SQLiteHelper.class.getSimpleName()," Error in Database copy "+e.getLocalizedMessage());
}
}
}
【问题讨论】:
-
应对时是否崩溃?
-
崩溃?如何?我们能看到崩溃吗?
-
@DIVA 是的,它正在与 SQLiteDatabaseCorruptException developer.android.com/reference/android/database/sqlite/… 一起崩溃
-
我猜复制有问题..它是否适用于小型数据库?你最近在 db 上做过任何升级吗?
-
没有对 Db 进行升级,是的,它非常适合小型 DB。
标签: android database sqlite android-assets