Comment s'amuser avec une bdd SQLite importée
Bonjour à tou-te-s,
je suis en train de réaliser une app dans laquelle je souhaite utiliser une bdd que j'ai importée. J'ai réussi à créer la bdd (pour info j'ai utilisé le module Firefox SQLite Manager qui est fort sympathique) et j'ai réussi à l'importer dans /data/data/mon_package/databases/.
J'ai ensuite créer 2 activity :
DataBaseHelper :
Code:
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
| 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;
public class DataBaseHelper extends SQLiteOpenHelper {
// Intialisation des variables principales
private static String DB_PATH = "/data/data/mon_package_avec_son_vrai_nom/databases/";
private static String DB_NAME = "bdonnees.sqlite";
private SQLiteDatabase myDataBase;
private final Context myContext;
/*
* Numero de version de la DB. Si ce numero change, la fonction onUpgrade
* est execute pour effacer le contenu de la DB et recrer la nouvelle
* version du schema.
*/
private static final int DATABASE_VERSION = 1;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
// db = getWritableDatabase();
this.myContext = context;
System.out.println("connexion bd ok");
}
// Creates a empty database on the system and rewrites it with your own
// database.
public void createDataBase() throws IOException {
System.out.println("creation");
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(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* 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 = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_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 + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
} |
et BddSqlActivity
Code:
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
| import java.io.IOException;
import android.app.Activity;
import android.database.SQLException;
import android.os.Bundle;
import fr.reseaulibre.bddsql.DataBaseHelper;
public class BddSqlActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//appel de la bdd
DataBaseHelper myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
System.out.println("lecture bdd possible");
}
catch(SQLException sqle){
System.err.println("grrr, probleme!");
throw sqle;
}
}
} |
Voici une partie de mon logcat:
Code:
1 2 3 4 5 6 7 8 9 10
| 03-27 14:37:12.435: D/ddm-heap(417): Got feature list request
03-27 14:37:12.635: I/System.out(417): connexion bd ok
03-27 14:37:12.635: I/System.out(417): creation
03-27 14:37:12.665: I/System.out(417): lecture bdd possible
03-27 14:37:12.735: W/InputManagerService(52): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@438a95d0 (uid=10001 pid=96)
03-27 14:37:12.775: I/ActivityManager(52): Displayed activity fr.monpackage.bddsql/.BddSqlActivity: 488 ms (total 488 ms)
03-27 14:37:12.925: W/ResourceType(96): Requesting resource 0x7f040000 failed because it is complex
03-27 14:37:12.935: W/PackageManager(96): Failure retrieving text 0x7f040000 in package fr.android.HelloListView
03-27 14:37:12.935: W/PackageManager(96): android.content.res.Resources$NotFoundException: String resource ID #0x7f040000
03-27 14:37:12.935: W/PackageManager(96): at android.content.res.Resources.getText(Resources.java:205) |
J'en déduis que j'arrive à me connecter à la bdd. Par contre je ne comprends pas la ligne avec un warning liée à un autre package.
Code:
03-27 14:37:12.935: W/PackageManager(96): Failure retrieving text 0x7f040000 in package fr.android.HelloListView
Voilà où j'en suis.
Dans ma mini-bdd se trouve 2 tables dont l'une nommée Do avec comme champs (Role, Poste, Telephone) avec quelques entrées pour chacuns d'eux.
Je souhaite pouvoir faire des requêtes et afficher (dans un textview pour commencer) la liste de tous les Role (par exemple).
Je pense avoir compris qu'il faille ajouter des methodes et un cursor dans DataBaseHelper et ensuite afficher le resultat dans BddSqlActivity mais je ne vois pas comment faire.
J'ai testé ce code à la fin de DataBaseHelper et dans BddSqlActivity:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
| public String getData(){
//String[] columns = new String[]{"Poste","Role"};
Cursor c = myDataBase.query("SELECT * FROM Do", null,null,null,null,null,null);
String result = " ";
int iPoste = c.getColumnIndex("Poste");
int iRole = c.getColumnIndex("Role");
for (c.moveToFirst(); !c.isAfterLast();c.moveToNext())
{
result = result + c.getString(iPoste) + c.getString(iRole) + "\n";
}
return result;
} |
Mais bon ça ne fonctionne pas du tout. Une étape m'échappe.
Une âme charitable (ou plusieurs) pourrait-elle m'aider, svp.