Android - Bases de datos

 
Vista:

Bases de datos

Publicado por HEIk (3 intervenciones) el 05/12/2017 17:47:53
Hola gente, estoy realizando una aplicación que debe acceder a una base de datos previamente creada por nosotros en otro programa(local creo que se llama). He encontrado por la red varias formas de acceder a dicha base de datos, pero en todos los casos me ocurre igual, en el momento que tiene que ejecutar esa parte se cierra la aplicación.
Si alguien pudiera ayudarme se lo agradecería mucho, podría aportar mas información sobre mi codigo si fuese preciso.
Muchas gracias!!!!!!!!!!!!!!!!!
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
-1
Responder
Imágen de perfil de xve
Val: 153
Bronce
Ha mantenido su posición en Android (en relación al último mes)
Gráfica de Android

Bases de datos

Publicado por xve (87 intervenciones) el 05/12/2017 18:45:08
pero.... nos puedes mostrar el código? a que tipo de base de datos intentas conectarte? estas utilizando Java en tu aplicación Android?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Bases de datos

Publicado por HEIk (3 intervenciones) el 05/12/2017 19:07:43
Hola, perdona por no subir el codigo, no queria saturar. Utilizo una base de datos que he creado con db browser sqlite, la cual he insertado con extension .sql en la carpeta assets.
Dejo aqui el codigo de la parte que me da problemas, si no fuese suficiente para entender podria subir todo el proyecto. Gracias!
EN EL MAIN ACTIVITY HAGO ESTO:
1
2
3
4
5
6
7
8
9
10
11
12
public void consulta(View v) {
	GestorSQLite admin = new GestorSQLite(getApplicationContext(), "preguntas", null, 1);
	SQLiteDatabase bd = admin.getWritableDatabase();
	int identificador=1;
	Cursor fila = bd.rawQuery( "select pregunta from preguntas where identificador=" + identificador, null);
	if (fila.moveToFirst()) {
		pregunta.setText(fila.getString(0));
	}
	else
		Toast.makeText(getApplicationContext(), "No hay alumno con ese numero", Toast.LENGTH_SHORT).show();
	bd.close();
}

ESTA ES LA CLASE QUE USO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class GestorSQLite extends SQLiteOpenHelper {
    public GestorSQLite(Context context, String nombre, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, nombre, factory, version);
 
 
    }
    public Context mContext;
 
    @Override
 
 
    public void onCreate(SQLiteDatabase db) {
        // Sentencias de creación de base de datos
        // db.execSQL("create table preguntas( identificador integer primary key,pregunta text)");
 
      InputStream is = null;
        try {
 
            is = mContext.getAssets().open("prueba.sql");
            if (is != null) {
                db.beginTransaction();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line = reader.readLine();
                while (!TextUtils.isEmpty(line)) {
                    db.execSQL(line);
                    line = reader.readLine();
                }
                db.setTransactionSuccessful();
            }
        } catch (Exception ex) {
            // Muestra log
        } finally {
            db.endTransaction();
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // Muestra log
                }
            }
        }
    }
 
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int versAnte, int versNue) {
        //db.execSQL("drop table if exists lista");
        //db.execSQL("create table lista(matricula integer primary key, nombre text)");
    }
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Bases de datos

Publicado por HEIk (3 intervenciones) el 05/12/2017 19:08:30
Hola, perdona por no subir el codigo, no queria saturar. Utilizo una base de datos que he creado con db browser sqlite, la cual he insertado con extension .sql en la carpeta assets.
Dejo aqui el codigo de la parte que me da problemas, si no fuese suficiente para entender podria subir todo el proyecto. Gracias!
EN EL MAIN ACTIVITY HAGO ESTO:
1
2
3
4
5
6
7
8
9
10
11
12
public void consulta(View v) {
GestorSQLite admin = new GestorSQLite(getApplicationContext(), "preguntas", null, 1);
SQLiteDatabase bd = admin.getWritableDatabase();
int identificador=1;
Cursor fila = bd.rawQuery( "select pregunta from preguntas where identificador=" + identificador, null);
if (fila.moveToFirst()) {
pregunta.setText(fila.getString(0));
}
else
Toast.makeText(getApplicationContext(), "No hay alumno con ese numero", Toast.LENGTH_SHORT).show();
bd.close();
}

ESTA ES LA CLASE QUE USO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class GestorSQLite extends SQLiteOpenHelper {
public GestorSQLite(Context context, String nombre, SQLiteDatabase.CursorFactory factory, int version) {
super(context, nombre, factory, version);
 
 
}
public Context mContext;
 
@Override
 
 
public void onCreate(SQLiteDatabase db) {
// Sentencias de creación de base de datos
// db.execSQL("create table preguntas( identificador integer primary key,pregunta text)");
 
InputStream is = null;
try {
 
is = mContext.getAssets().open("prueba.sql");
if (is != null) {
db.beginTransaction();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (!TextUtils.isEmpty(line)) {
db.execSQL(line);
line = reader.readLine();
}
db.setTransactionSuccessful();
}
} catch (Exception ex) {
// Muestra log
} finally {
db.endTransaction();
if (is != null) {
try {
is.close();
} catch (IOException e) {
// Muestra log
}
}
}
}
 
 
@Override
public void onUpgrade(SQLiteDatabase db, int versAnte, int versNue) {
//db.execSQL("drop table if exists lista");
//db.execSQL("create table lista(matricula integer primary key, nombre text)");
}
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar