IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

Problème avec SQLite


Sujet :

Android

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2015
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2015
    Messages : 14
    Par défaut Problème avec SQLite
    Bonjour, j'aimerais me familiariser avec les BDD sous Android et me retrouve face à un problème que je n'arrive pas à résoudre.
    Ma BDD est composée de 5 champs :
    • un champ "id" qui est la clé primaire en autoincrement
    • un champ appelé "champ1"
    • un champ appelé "champ2"
    • un champ appelé "champ3"
    • un champ appelé "lien"


    Mon projet se compose de 4 classes :
    • ma classe Alerte qui est composée du constructeur, des getteurs et setteurs :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    public class Alerte {
     
        private static int id;
        private static String val_champ1;
        private static String val_champ2;
        private static String val_champ3;
        private static String val_lien;
     
        public Alerte(){}
     
        public Alerte(String champ1, String champ2, String champ3, String lien){
            this.val_champ1=champ1;
            this.val_champ2=champ2;
            this.val_champ3=champ3;
            this.val_lien=lien;
        }
     
        public static int getId() {
            return id;
        }
     
        public void setId(int id) {
            this.id = id;
        }
     
        public static String getChamp1() {
            return val_champ1;
        }
     
        public void setChamp1(String champ1) {
            this.val_champ1 = champ1;
        }
     
        public static String getChamp2() {
            return val_champ2;
        }
     
        public void setChamp2(String champ2) {
            this.val_champ2 = champ2;
        }
     
        public static String getChamp3() {
            return val_champ3;
        }
     
        public void setChamp3(String champ3) {
            this.val_champ3 = champ3;
        }
     
        public static String getLien(){return val_lien;}
     
        public void setLien(String lien){
            this.val_lien=lien;
        }
     
        // Sera utilisée par ArrayAdapter dans la ListView
        @Override
        public String toString() {
            return "numero d'alerte : " + id + "\nchamp 1:" + val_champ1 + "\nchamp 2:" + val_champ2
                    + "\nchamp 3: " + val_champ3 + "lien: " + val_lien;
        }
    }
    • ma classe MaBaseSQlite qui est chargée de définir la table lors de l'instanciation :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    public class MaBaseSQLite extends SQLiteOpenHelper {
     
        public static final String TABLE_ALERTE = "table_alerte";
        public static final String COL_ID = "id";
        public static final String COL_ID_CHAMP1 = "champ1";
        public static final String COL_ID_CHAMP2 = "champ2";
        public static final String COL_ID_CHAMP3 = "champ3";
        public static final String COL_ID_LIEN = "lien";
     
        private static final String DATABASE_NAME = "alerte.db";
        private static final int DATABASE_VERSION = 1;
     
        // Commande sql pour la création de la base de données
        private static final String CREATE_DATABASE = "CREATE TABLE " + TABLE_ALERTE + " ("
                + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_ID_CHAMP1 + " TEXT, "
                + COL_ID_CHAMP2 + " TEXT, " + COL_ID_CHAMP3 + " TEXT, " + COL_ID_LIEN + " TEXT ) ;";
     
        public MaBaseSQLite(Context context, String name, SQLiteDatabase.CursorFactory factory,
                            int version){
            super (context, name, factory, version);
        }
     
        @Override
        public void onCreate(SQLiteDatabase db){
            db.execSQL(CREATE_DATABASE);
        }
     
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            //pour l'instant il on supprime juste la vieille base pour enregistrer la nouvelle.
            //a modifier après pour ajouter à la suite
            db.execSQL("DROP TABLE "+TABLE_ALERTE+";" );
        }
    }
    • ma class AlerteBDD qui permet l'ajout, la suppression, la modification et requêtes pour récupérer le contenu de la BDD :


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    public class AlerteBDD {
        private static final String DATABASE_NAME = "alerte.db";
        private static final int DATABASE_VERSION = 1;
     
        private static final String TABLE_ALERTE = "table_alerte";
        private static final String COL_ID = "id";
        private static final int NUM_COL_ID = 0;
        private static final String COL_CHAMP1 = "champ1";
        private static final int NUM_COL_CHAMP1 = 1;
        private static final String COL_CHAMP2 = "champ2";
        private static final int NUM_COL_CHAMP2 = 2;
        private static final String COL_CHAMP3 = "champ3";
        private static final int NUM_COL_CHAMP3 = 3;
        private static final String COL_LIEN = "lien";
        private static final int NUM_COL_LIEN = 4;
     
        private SQLiteDatabase bdd;
     
        private MaBaseSQLite maBaseSQLite;
        public AlerteBDD(Context context){
            //creation bdd et table
            maBaseSQLite = new MaBaseSQLite(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
     
        public void open(){
            //ouverture bdd en ecriture
            bdd = maBaseSQLite.getWritableDatabase();
        }
     
        public void close(){
            //fermeture bdd
            bdd.close();
        }
     
        public SQLiteDatabase getBDD(){
            return bdd;
        }
     
        public long insertAlerte(Alerte alerte){
            //creation d'un ContentValues (fonctionne comme HashMap)
            ContentValues values = new ContentValues();
            //values.put(COL_ID,Alerte.getId());
            values.put(COL_CHAMP1, Alerte.getChamp1());
            values.put(COL_CHAMP2, Alerte.getChamp2());
            values.put(COL_CHAMP3, Alerte.getChamp3());
            values.put(COL_LIEN, Alerte.getLien());
            return bdd.insert(TABLE_ALERTE, null, values);
        }
     
        public int updateAlerte(int id, Alerte alerte){
            //update BDD avec ID
     
            ContentValues values = new ContentValues();
            values.put(COL_ID,Alerte.getId());
            values.put(COL_CHAMP1, Alerte.getChamp1());
            values.put(COL_CHAMP2, Alerte.getChamp2());
            values.put(COL_CHAMP3, Alerte.getChamp3());
            values.put(COL_LIEN, Alerte.getLien());
            return  bdd.update(TABLE_ALERTE, values, COL_ID + " = " + id, null);
        }
     
        public int removeAlerteWithId(int id){
            //suppression BDD avec ID
            return  bdd.delete(TABLE_ALERTE, COL_ID + " = " + id, null);
        }
     
        public Alerte getAlerteWithChamp1(String chmp1){
            Cursor c = bdd.query(TABLE_ALERTE, new String[]{ COL_CHAMP1,
                    COL_CHAMP2, COL_CHAMP3, COL_LIEN}, COL_CHAMP1 + " LIKE \""
                    + chmp1 + "\n", null, null, null, null);
            return cursorToAlerte(c);
        }
     
        private Alerte cursorToAlerte(Cursor c){
            //si aucun element retourné dans requête, on renvoie null
            if(c.getCount()==0)
                return  null;
     
            //sinon on se deplace sur le premier element
            c.moveToFirst();
            //creation d'une Alerte
            Alerte alerte = new Alerte();
            //alerte.setId(c.getInt(NUM_COL_ID));
            alerte.setChamp1(c.getString(NUM_COL_CHAMP1));
            alerte.setChamp2(c.getString(NUM_COL_CHAMP2));
            alerte.setChamp3(c.getString(NUM_COL_CHAMP3));
            alerte.setLien(c.getString(NUM_COL_LIEN));
            return alerte;
        }
    }
    • enfin il y a ma MainClass, classe dans laquelle je modifie ma BDD "en dur" et j'affiche le contenu de la base dans des Toasts :



    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    public class MainClass extends Activity {
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_activity);
     
            //creation instance de classe AlerteBDD
            AlerteBDD alerteBDD = new AlerteBDD(this);
     
             //creation alerte
            Alerte alerte = new Alerte( "champ1", "champ2", "champ3", "adresse du lien");
     
            alerteBDD.open();
     
            alerteBDD.insertAlerte(alerte);
     
     
             Alerte alerteFromBDD = alerteBDD.getAlerteWithChamp1(alerte.getChamp1());
     
           if (alerteFromBDD != null){
                Toast.makeText(this, alerteFromBDD.toString(), Toast.LENGTH_LONG).show();
                alerteFromBDD.setChamp1("le champ 1 a ete modifie");
                alerteBDD.updateAlerte(alerteFromBDD.getId(), alerteFromBDD);
                }
     
            alerteFromBDD = alerteBDD.getAlerteWithChamp1("le champ 1 a ete modifie");
            if (alerteFromBDD!=null){
                Toast.makeText(this, alerteFromBDD.toString(), Toast.LENGTH_LONG).show();
                alerteBDD.removeAlerteWithId(alerteFromBDD.getId());
     
            }
            alerteFromBDD = alerteBDD.getAlerteWithChamp1("le champ 1 a ete modifie");
     
            if(alerteFromBDD==null){
                Toast.makeText(this,"Alerte inexistante dans la BDD", Toast.LENGTH_LONG).show();
            }
            else{
                Toast.makeText(this, "Alerte existante dans la BDD", Toast.LENGTH_LONG).show();
            }
            alerteBDD.close();
        }
    }
    Lors de l'execution de ce code je me retrouve avec ces messages d'erreurs :


    07-28 16:48:15.471 18348-18348/com.example.stransitic.octempo E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stransitic.octempo/com.example.stransitic.octempo.MainClass}: android.database.sqlite.SQLiteException: unrecognized token: ""champ1": , while compiling: SELECT champ1, champ2, champ3, lien FROM table_alerte WHERE champ1 LIKE "champ1
    (...)
    Caused by: android.database.sqlite.SQLiteException: unrecognized token: ""champ1": , while compiling: SELECT champ1, champ2, champ3, lien FROM table_alerte WHERE champ1 LIKE "champ1
    (...)
    at com.example.stransitic.octempo.AlerteBDD.getAlerteWithChamp1(AlerteBDD.java:79)
    at com.example.stransitic.octempo.MainClass.onCreate(MainClass.java:28)

    Je n'arrive pas à comprendre ou se trouve mon erreur.
    J'espère avoir été assez clair dans mes explications !
    Simon

  2. #2
    Expert confirmé

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Billets dans le blog
    3
    Par défaut
    Facile il manque un " après la valeur...

    Mais sinon il ne faut surtout pas faire comme cela pour passer un paramètre (construire la clause soit même).
    L'utilisation de paramètres non seulement permet d'éviter ce genre de problème, mais permet aussi la base d'optimiser la requête (si réutilisée souvent)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    Cursor c = null;
    try {
        c = bdd.query(TABLE_ALERTE, 
                        new String[] { COL_CHAMP1, COL_CHAMP2, COL_CHAMP3, COL_LIEN}, 
                        COL_CHAMP1 + " LIKE ?", // <= on utilise ? pour spécifier un paramètre
                        new String[] { chmp1 } ,  // <= on passe le paramètre
                        null, null, null);
        return c.moveToFirst() ? cursorToAlerte(c) : null;  // <= si pas de résultat ... pas la peine de passer par la fonction !
    } finally {
        if (c != null) c.close(); // <= on n'oublie pas de fermer le cursor !
    }

  3. #3
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2015
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2015
    Messages : 14
    Par défaut
    J'ai bien rectifié le problème de guillemet, mais je me retrouve quand même avec des erreurs :


    07-28 17:39:54.491 12606-12606/com.example.stransitic.octempo E/SQLiteDatabase﹕ Error inserting lien=adresse du lien champ3=champs3 champ1=champ1 champ2=champs2
    android.database.sqlite.SQLiteException: table table_alerte has no column named champ1: , while compiling: INSERT INTO table_alerte(lien,champ3,champ1,champ2) VALUES (?,?,?,?)
    (...)
    at com.example.stransitic.octempo.AlerteBDD.insertAlerte(AlerteBDD.java:58)
    at com.example.stransitic.octempo.MainClass.onCreate(MainClass.java:25)
    (...)
    07-28 17:39:54.511 12606-12606/com.example.stransitic.octempo E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stransitic.octempo/com.example.stransitic.octempo.MainClass}: android.database.sqlite.SQLiteException: no such column: champ1: , while compiling: SELECT id, champ1, champ2, champ3, lien FROM table_alerte WHERE id LIKE "champ1"
    (...)
    Caused by: android.database.sqlite.SQLiteException: no such column: champ1: , while compiling: SELECT id, champ1, champ2, champ3, lien FROM table_alerte WHERE id LIKE "champ1"
    (...)
    at com.example.stransitic.octempo.AlerteBDD.getAlerteWithChamp1(AlerteBDD.java:79)
    at com.example.stransitic.octempo.MainClass.onCreate(MainClass.java:27)

    Je ne comprends pas pourquoi dans le premier message d'alerte, les champs de ma table_alerte ne sont pas dans le bon ordre, enfin.. je comprends pas non plus les autres, mais ça, ça me laisse particulièrement perplexe..

  4. #4
    Expert confirmé

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Billets dans le blog
    3
    Par défaut
    table table_alerte has no column named champ1
    Ce qui veut dire: la table "table_alerte" dans la database n'a pas de colonne portant le nom "champ1"

    Je vois que la base est en version 1, la table a toujours été créée avec la colonne "champ1" ?
    Sinon, il faut upgrader la table, ou faire une réinstallation de l'application (plutot qu'une mise à jour).

  5. #5
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2015
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2015
    Messages : 14
    Par défaut
    Hey !
    Cetait bien un problème de version de BDD, mon projet marche bien maintenant !
    Merci du coup de main !

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. problème avec sqlite
    Par nagca dans le forum Android
    Réponses: 1
    Dernier message: 08/06/2011, 10h08
  2. Réponses: 4
    Dernier message: 25/06/2010, 17h05
  3. Problème avec Sqlite lors de la compilation
    Par Jiyuu dans le forum Déploiement/Installation
    Réponses: 6
    Dernier message: 28/11/2009, 18h32
  4. [C#]problème avec SqLite
    Par ClaudeBg dans le forum Linq
    Réponses: 8
    Dernier message: 18/06/2009, 16h17
  5. Problème avec SQLITE
    Par Jiyuu dans le forum Django
    Réponses: 2
    Dernier message: 12/03/2009, 07h07

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo