我的应用程序(平台1.5)有一个预先填充的数据库。 Sqlite文件大于5mb,因此我将其拆分为小于950KB的小文件并将它们放入Assets。
首次安装应用时,它会将所有这些文件复制到一个数据库文件中。 它在我自己的手机(三星GalaxyS 2.2)中运行良好。但是,我在samsung gt-s5830i 2.3.6中尝试了它,当它加载数据库时,它会崩溃。
我不知道为什么它不起作用。请帮帮我。
这是我的代码:
公共类SQLiteDBHelper扩展了SQLiteOpenHelper {
private static final String DB_PATH = "/data/data/com.android.appname/databases/";
private static final String DB_NAME = "db.sqlite";
private static final String ASSETS_DB_FOLDER = "db";
private SQLiteDatabase myDataBase;
private final Context myContext;
public SQLiteDBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and overwrite it with your own
* database.
**/
public void createDatabase() throws IOException {
boolean dbExist = checkDatabase();
if (!dbExist) {
super.getReadableDatabase();
try {
copyDatabase();
}
catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY|SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}
catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDatabase() throws IOException {
String[] dbFiles = myContext.getAssets().list(ASSETS_DB_FOLDER);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
for(int i =0; i < dbFiles.length; i++) {
InputStream myInput = myContext.getAssets().open(ASSETS_DB_FOLDER+"/"+dbFiles[i]);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
}
myOutput.flush();
myOutput.close();
}
public void openDatabase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY|SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}
@Override
public synchronized void close() {
if (myDataBase != null) myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) { }
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
@Override
public synchronized SQLiteDatabase getReadableDatabase (){
try {
createDatabase();
openDatabase();
}
catch (SQLException e) {
myDataBase = null;
e.printStackTrace();
}
catch (IOException e) {
myDataBase = null;
e.printStackTrace();
}
return myDataBase;
}
}