Buen Dia.
Tengo una base de datos en la carpeta assets y deseo copiarla la carpeta databases de mi aplicacion, para eso uso una clase:
public class DbOpenHelper extends SQLiteOpenHelper
{
private static DbOpenHelper _dbHelper;
private Context context;
private DbOpenHelper(Context contexto)
{
super(contexto, DbHelper.DATABASE_NAME, null, DbHelper.DATABASE_VERSION);
this.context=contexto;
try
{
createDataBase();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static DbOpenHelper getInstance(Context context)
{
if(_dbHelper == null)
{
_dbHelper = new DbOpenHelper(context);
}
return _dbHelper;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException
{
boolean dbExist = checkDataBase();
if(dbExist)
{
//do nothing - database already exist
}
else
{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.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()
{
String myPath = DbHelper.DB_PATH + DbHelper.DATABASE_NAME;
File dbFile = new File(myPath);
return dbFile.exists();
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException
{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DbHelper.DATABASE_NAME);
// Path to the just created empty db
String outFileName = DbHelper.DB_PATH + DbHelper.DATABASE_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
@Override
public void onCreate(SQLiteDatabase db)
{
Log.d("Errores","Entro OnCreate Open Helper");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
La base de datos es creada y copiada con exito a la carpeta databases de mi aplicacion, pero cuando hago el query la primera vez la aplicacion no encuentra la tabla, despues de que sale la excepcion ya la segunda vez funciona perfecto.
Envio la excepcion y el codigo donde hago el query.