Problema OpenHelper Android

89 views
Skip to first unread message

Julio Galeano

unread,
Jan 30, 2012, 9:56:48 AM1/30/12
to desarrollad...@googlegroups.com
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.

public DbHelper(Context contexto)
{
dbOpenHelper = DbOpenHelper.getInstance(contexto);
}

private void open() throws SQLiteException
{
try
{
db = dbOpenHelper.getWritableDatabase();
catch (SQLiteException ex)
{
db = dbOpenHelper.getReadableDatabase();
}
}

private void close()
{
db.close();
}

public Etb getStep(int idStep, int option)
{
Etb etbObj = null;
open();
Cursor cursor=db.query(SUPPORT_TABLE, null, "id = "+idStep+" AND option = "+option, null, null, null, null);
if(cursor.moveToFirst())
{
int relationId = cursor.getInt(RELATION_COLUMN);
cursor=db.query(SUPPORT_TABLE, null, "id = "+relationId, null, null, null, null);
if(cursor.moveToFirst())
{
etbObj= new Etb();
List<Integer> options = new ArrayList<Integer>(2);
etbObj.setId(cursor.getInt(ID_COLUMN));
etbObj.setDescription(cursor.getString(DESCRIPTION_COLUMN));
do
{
options.add(cursor.getInt(OPTION_COLUMN));
}while(cursor.moveToNext());
etbObj.getOptions().addAll(options);
}
}
close();
return etbObj;
}

01-30 14:38:46.048: E/AndroidRuntime(3365): Caused by: android.database.sqlite.SQLiteException: no such table: support: , while compiling: SELECT * FROM support WHERE id = 0 AND option = 0
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.database.sqlite.SQLiteProgram.native_compile(Native Method)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.database.sqlite.SQLiteProgram.compile(SQLiteProgram.java:110)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:49)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:49)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1118)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1006)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:964)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1041)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at <Mi Paquete>.DbHelper.getStep(DbHelper.java:57)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at <Mi Paquete>.TechnicalSupportView.initLogig(TechnicalSupportView.java:36)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at <Mi Paquete>.TechnicalSupportView.onCreate(TechnicalSupportView.java:28)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
01-30 14:38:46.048: E/AndroidRuntime(3365):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
01-30 14:38:46.048: E/AndroidRuntime(3365):  ... 26 more

Ya le hice Debug y la aplicacion si crea la base de datos antes de hacer el query pero por alguna razon no encuenta la tabla. Creo que el problema es de timeming pero no se como solucionarlo.

Agradesco de antemano la colaboracion.

Julio C



Juan de Dios Maldonado Sánchez

unread,
Jan 30, 2012, 10:50:03 AM1/30/12
to desarrollad...@googlegroups.com
Una cosa es que exista la base de datos y otra cosa distinta es que exista una tabla dentro de una base de datos. Míralo, porque el error te está diciendo que aunque existe la base de datos, no existe la tabla que indicas.




--
Has recibido este mensaje porque estás suscrito al grupo "desarrolladores-android" de Grupos de Google.
Para publicar una entrada en este grupo, envía un correo electrónico a desarrollad...@googlegroups.com.
Para anular tu suscripción a este grupo, envía un correo electrónico a desarrolladores-a...@googlegroups.com
Para tener acceso a más opciones, visita el grupo en http://groups.google.com/group/desarrolladores-android?hl=es.



--
An'Brain - Prueba el nuevo widget inteligente para tu Android.
Idiotizer Free - Idiotiza a tus amigos. (Se requieren auriculares)
Track My App - Realiza un seguimiento de tus aplicaciones en el Android market.

Julio Galeano

unread,
Jan 30, 2012, 10:51:56 AM1/30/12
to desarrollad...@googlegroups.com
Tienes toda la razon, me falto explicar que yo reviso la base de datos y es creada con exito, con todas sus tablas, cuando hice el debug antes de hacer la consulta reviso la base de datos y esta con todos sus datos, tablas y todo correcto.

Julio C

Juan de Dios Maldonado Sánchez

unread,
Jan 30, 2012, 11:05:36 AM1/30/12
to desarrollad...@googlegroups.com
Entonces no te estás abriendo la base de datos que crees que estás abriendo.

Julio Galeano

unread,
Jan 30, 2012, 11:26:26 AM1/30/12
to desarrollad...@googlegroups.com
cuando hago el openDatabase me retorna un objeto no null, como hago para saber que la apertura fue echa correctamente?
Reply all
Reply to author
Forward
0 new messages