PDA

Ver la Versión Completa : Clase DBHelper


bb_android
05/02/13, 23:34:57
Hola he bajado esta clase dbhelper de la web para hacer consultas a una base de datos sqlite

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class AnyDBAdapter {

private static final String TAG = "AnyDBAdapter";
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;

//make sure this matches the
//package com.MyPackage;
//at the top of this file
private static String DB_PATH = "/data/data/com.example.noritex/databases/";

//make sure this matches your database name in your assets folder
// my database file does not have an extension on it
// if yours does
// add the extention
private static final String DATABASE_NAME = "Noritex";

//Im using an sqlite3 database, I have no clue if this makes a difference or not
private static final int DATABASE_VERSION = 3;

private final Context adapterContext;

public AnyDBAdapter(Context context) {
this.adapterContext = context;
}

public AnyDBAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(adapterContext);

try {
mDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}

try {
mDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
return this;
}
//Usage from outside
// AnyDBAdapter dba = new AnyDBAdapter(contextObject); //in my case contextObject is a Map
// dba.open();
// Cursor c = dba.ExampleSelect("Rawr!");
// contextObject.startManagingCursor(c);
// String s1 = "", s2 = "";
// if(c.moveToFirst())
// do {
// s1 = c.getString(0);
// s2 = c.getString(1);
// } while (c.moveToNext());
// dba.close();
public Cursor ExampleSelect(String query ,String myVariable)
{
//String query = "SELECT locale, ? FROM android_metadata";
return mDb.rawQuery(query, new String[]{myVariable});
}

//Usage
// AnyDBAdatper dba = new AnyDBAdapter(contextObjecT);
// dba.open();
// dba.ExampleCommand("en-CA", "en-GB");
// dba.close();
public void ExampleCommand(String myVariable1, String myVariable2)
{
String command = "INSERT INTO android_metadata (locale) SELECT ? UNION ALL SELECT ?";
mDb.execSQL(command, new String[]{ myVariable1, myVariable2});
}

public void close() {
mDbHelper.close();
}

private static class DatabaseHelper extends SQLiteOpenHelper {

Context helperContext;

DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
helperContext = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database!!!!!");
//db.execSQL("");
onCreate(db);
}

public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {

//make sure your database has this table already created in it
//this does not actually work here
/*
* db.execSQL("CREATE TABLE IF NOT EXISTS \"android_metadata\" (\"locale\" TEXT DEFAULT 'en_US')"
* );
* db.execSQL("INSERT INTO \"android_metadata\" VALUES ('en_US')"
* );
*/
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}

public SQLiteDatabase getDatabase() {
String myPath = DB_PATH + DATABASE_NAME;
return SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}

private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException {

// Open your local db as the input stream
InputStream myInput = helperContext.getAssets().open(DATABASE_NAME);

// Path to the just created empty db
String outFileName = DB_PATH + 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();
}

public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DATABASE_NAME;
mDb = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}

@Override
public synchronized void close() {

if (mDb != null)
mDb.close();

super.close();

}
}

}


my duda es la siguiente
como debo hacer el llamado a la funcion ExampleSelect para hacer la consulta de los datos?

muchas gracias por toda la ayuda brindada!

set92
06/02/13, 10:51:34
En serio lo preguntas? Lo vuelvo a copiar haber si te fijas...
//Usage from outside

// AnyDBAdapter dba = new AnyDBAdapter(contextObject); //in my case contextObject is a Map

// dba.open();

// Cursor c = dba.ExampleSelect("Rawr!");

// contextObject.startManagingCursor(c);

// String s1 = "", s2 = "";

// if(c.moveToFirst())

// do {

// s1 = c.getString(0);

// s2 = c.getString(1);

// } while (c.moveToNext());

// dba.close();

public Cursor ExampleSelect(String query ,String myVariable)
{
//String query = "SELECT locale, ? FROM android_metadata";

returnmDb.rawQuery(query, new String[]{myVariable});
}

Ahora te fijas? Vamos que estaba abriendo mi eclipse para copiarte un cursor y una select pero coño, todo eso comentado te pone el modo de uso y como se hace todo.

Es decir te dice que devuelve un curso y que tienes que pasarle la query/select y la variable, y en la parte de dentro del metodo te enseñan como es una query.

Y en la parte de arriba es que te explican hasta que tienes que crear un objeto de la clase AnyDBAdapter en la que le pases el contexto, luego tienes que abrir la conexion con la BD, creas un curso y le mandas en este caso solo la variable, me imagino que porque la query ya la ha metido a manija dentro del metodo, y lo que devuelva esta query se almacenara en el cursor C, y por ultimo va rellenando s1 y s2 con los datos recojidos de la BD. Y bueno la ultima linea que lo que hace es cerrar la conexion con la BD.

Si no has entendido eso con el pedazo ejemplo que te viene mirate en sgoliver por ejemplo el tutorial que tiene de BD porque significaria que te falta la base y eso ya necesitas que te lo expliquen bien y que se te quede.

bb_android
06/02/13, 15:30:43
ok! lo he visto, muchas gracias . he bajado el tutorial de sgoliver tambien. tengo todavia una duda el // contextObject.startManagingCursor(c);
como lo declaro en la clase de la de la pantalla? me manda este error
The method startManagingCursor(Cursor) is undefined for the type Context