Could someone guide me? I've been involved with this for a couple of days and it fails.
I have a SQLite .db file that contains an empty database. the idea is to copy it to my android application from the assets directory, which is located in src / main / assets.
But something is failing and I do not know what it is. I suspect where the fault is, but I can not find the key. I create a database, but it creates it empty (without tables).
For help, the DB file is this:
My code is as follows:
private String DB_PATH;
private static String DB_NAME = "organizapp.db";
...
* Crea una base de datos vacía en el sistema y la reescribe con nuestro
* fichero de base de datos.
* */
private void createDataBase(){
boolean dbExist = checkDataBase();
this.getWritableDatabase();
if(!dbExist) {
try {
copyDataBase();
} catch (IOException e) {
throw new Error(myContext.getString(R.string.error_copiando_bd));
}
}
}
/**
* Comprueba si la base de datos existe para evitar copiar siempre el
* fichero cada vez que se abra la aplicación.
* @return true si existe, false si no existe
*/
public boolean checkDataBase(){
SQLiteDatabase checkDB = null;
Log.d("Comprobando bd","Objeto a null");
try{
checkDB = SQLiteDatabase
.openDatabase(this.DB_PATH,
null,
SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
Log.d("Creando bd","No hay bd.");
//si llegamos aqui es porque la base de datos no existe todavía.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copia nuestra base de datos desde la carpeta assets a la recién creada
* base de datos en la carpeta de sistema, desde dónde podremos acceder a
* ella.
* Esto se hace con bytestream.
* */
private void copyDataBase() throws IOException{
Log.d("Copiando db","entramos.");
//Abrimos el fichero de base de datos como entrada
InputStream myInput = myContext.getAssets().open(DB_NAME);
Log.d("Creando bd","Abrimos"+DB_NAME);
//Ruta a la base de datos vacía recién creada
String outFileName = getDB_PATH();
Log.d("Creando bd","apuntamos a "+getDB_PATH());
//Abrimos la base de datos vacía como salida
OutputStream myOutput = new FileOutputStream(outFileName);
//Transferimos los bytes desde el fichero de entrada al de salida
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Liberamos los streams
myOutput.flush();
myOutput.close();
myInput.close();
Log.d("Creando bd","BD Copiada");
}
What am I doing wrong?
Thanks in advance.