我已經看過有關包括預填充的sqlite數據庫的文章,但我仍然收到錯誤。這裏是我的數據庫Helper類:不能在Android項目中包含預填充的sqlitedatabase
public class MyDBHelper extends SQLiteOpenHelper {
private static MyDBHelper mInstance = null;
private static final int DB_VERSION = 5;
private static final String DB_NAME = "database.sqlite";
static final String TABLE_NAME = "PRODUCTS";
private final Context mContext;
private static SQLiteDatabase myWritableDb;
private static final String DATABASE_PATH = "/data/data/com.example.barcodescanner/databases/";
public static MyDBHelper getInstance(Context ctx) {
if (mInstance == null) {
mInstance = new MyDBHelper(ctx.getApplicationContext());
}
return mInstance;
}
private MyDBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.mContext = context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
public void createDatabase() throws IOException {
createDB();
}
private void createDB() throws IOException {
boolean dbExist = DBExists();
if (!dbExist) {
this.getReadableDatabase();
copyDBFromResource();
}
}
private boolean DBExists() {
File dbFile = new File(DATABASE_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDBFromResource() throws IOException {
InputStream inputStream = null;
OutputStream outStream = null;
String dbFilePath = DATABASE_PATH + DB_NAME;
try {
inputStream = mContext.getAssets().open(DB_NAME);
outStream = new FileOutputStream(dbFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
outStream.flush();
outStream.close();
inputStream.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion,
int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
我創建像數據庫中的以下內容:
public MyDBHelper helper = MyDBHelper.getInstance(this);
helper.createDatabase();
的問題是,在copyDBFromResource功能,在下面一行:
outStream = new FileOutputStream(dbFilePath);
我得到一個異常說
java.io.FileNotFoundException: /data/data/com.example.barcodescanner/databases/database.sqlite: open failed: ENOENT (No such file or directory)
我在做什麼錯?我的DATABASE_PATH變量中的軟件包名稱是MainActivity所在的軟件包名稱。那是錯的嗎?任何人都可以幫我解決它嗎?
感謝
如果你**擺脫**的DATABASE_PATH怎麼辦?這個對我有用。 –
請使用'SQLiteAssetHelper'打包數據庫,以便與您的應用程序一起分發:https://github.com/jgilfelt/android-sqlite-asset-helper – CommonsWare