我创建了一个sqlite数据库,并将.db文件复制到应用程序的assets文件夹中,如问题2605555所述。代码编译得很好。在运行时,它表示无法读取文件。
我想使用readymade.db文件,并且只想在数据库不存在的情况下创建数据库。
需要帮助使用.db文件创建数据库。
@Override
public void onCreate(SQLiteDatabase db) {
File file=new File("YOUR DBfile PATH");
db.openOrCreateDatabase(file,null,CREATE_IF_NECESSARY);
}
package com.airi.buyue.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import com.airi.buyue.BuyueApp;
import com.airi.buyue.R;
import com.airi.buyue.util.FileUtils;
import com.airi.buyue.util.Utilities;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class DataManager {
public static final String DB_NAME = "zonen.db";
public static final String TABLE_NAME = "m_nzone_copy";
private SQLiteDatabase database;
private final Context context;
public DataManager(Context context) {
this.context = context;
getPath();
}
public SQLiteDatabase getDatabase() {
return database;
}
public void setDatabase(SQLiteDatabase database) {
this.database = database;
}
public void openDatabase() {
this.database = this.openDatabase(getPath() + "/" + DB_NAME);
}
public String getPath(){
String DATABASE_PATH;
if (!Utilities.isSdcardExisting()) {
DATABASE_PATH = BuyueApp.get().getFilesDir().getPath();
}else{
DATABASE_PATH = Environment.getExternalStorageDirectory().getPath();
}
return DATABASE_PATH;
}
public boolean needCreate() {
String dbfile = getPath() + "/" + DB_NAME;
try {
if (!(new File(dbfile).exists())) {
return true;
}
FileUtils.updateFile(dbfile);
return false;
} catch (Throwable ignored) {
}
return true;
}
private SQLiteDatabase openDatabase(String dbfile) {
try {
if (!(new File(dbfile).exists())) {
InputStream is = this.context.getResources().openRawResource(R.raw.zone);
FileOutputStream fos = new FileOutputStream(dbfile);
int BUFFER_SIZE = 400000;
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
FileUtils.updateFile(dbfile);
return SQLiteDatabase.openOrCreateDatabase(dbfile,null);
} catch (FileNotFoundException ignored) {
} catch (IOException ignored) {
} catch (Throwable ignored) {
}
return null;
}
public void closeDatabase() {
if(this.database!=null){
this.database.close();
}
}
}