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 Studio Java Discussion :

[Android Studio] Base de données


Sujet :

Android Studio Java

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    149
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 149
    Points : 59
    Points
    59
    Par défaut [Android Studio] Base de données
    Bonjour,

    je suis en train de développer une application, et j'aimerais utiliser une base de donnée pour stocker des données, je m'explique :
    Dans un layout, j'utilisateur va renseigner des champs afin de passer une commande de pot de peinture (nbr de pot, % de rouge, % de bleu et % de vert), puis appuie sur le bouton passer la commande, qui aura pour conséquence de stocker ces données dans la bdd. Dans une autre page, l'utilisateur pourrais retrouver les commandes passées qui s'afficheront dans un tableau.
    Mes questions sont donc :
    - pouvez-vous me donner une piste pour créer cette bdd, car j'ai cherché sur Internet mais je n'ai pas trouvé de tuto "simple" ? Je sais juste qu'il faut utiliser SQLite ^^
    - Pour l'affichage, est-il possible de créer n lignes dans le tableau en fonction du nombre de données entrées dans la bdd ?

    J'aimerais juste avoir quelques pistes pour mon problème ;-)

    Merci d'avance !

  2. #2
    Modérateur
    Avatar de grunk
    Homme Profil pro
    Lead dév - Architecte
    Inscrit en
    Août 2003
    Messages
    6 692
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Côte d'Or (Bourgogne)

    Informations professionnelles :
    Activité : Lead dév - Architecte
    Secteur : Industrie

    Informations forums :
    Inscription : Août 2003
    Messages : 6 692
    Points : 20 243
    Points
    20 243
    Par défaut
    T'as pas du chercher des masses : Android database sur google te donne en premier lien la doc officiel sur le sujet :
    http://developer.android.com/trainin...databases.html

    La notion de tableau ne me semble pas adaptée à ce que tu veux faire pour l'affichage.
    Une listeview semble plus simple.

  3. #3
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Citation Envoyé par oieretxe Voir le message
    Bonjour,

    je suis en train de développer une application, et j'aimerais utiliser une base de donnée pour stocker des données, je m'explique :
    Dans un layout, j'utilisateur va renseigner des champs afin de passer une commande de pot de peinture (nbr de pot, % de rouge, % de bleu et % de vert), puis appuie sur le bouton passer la commande, qui aura pour conséquence de stocker ces données dans la bdd. Dans une autre page, l'utilisateur pourrais retrouver les commandes passées qui s'afficheront dans un tableau.
    Mes questions sont donc :
    - pouvez-vous me donner une piste pour créer cette bdd, car j'ai cherché sur Internet mais je n'ai pas trouvé de tuto "simple" ? Je sais juste qu'il faut utiliser SQLite ^^
    - Pour l'affichage, est-il possible de créer n lignes dans le tableau en fonction du nombre de données entrées dans la bdd ?

    J'aimerais juste avoir quelques pistes pour mon problème ;-)

    Merci d'avance !
    Réponse à la question 1 : utilise SqlLite comme t'as indiqué grunk
    Réponse à la question 2 : tu peux utiliser une ListView avec un adaptateurs personnalisé ou non.

  4. #4
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    149
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 149
    Points : 59
    Points
    59
    Par défaut
    Bonjour,

    j'ai avancé sur la création de ma bdd, mais j'aimerais avoir votre avis sur ce que j'ai déjà fait, car je ne sais pas si je suis sur la bonne voie. J'ai suivi un tuto trouvé sur un autre site.

    J'ai créé 3 classes, la première est la classe Commande :
    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
    public class Commande {
     
        private int id;
        private String date;
        private String heure;
        private int pourcentage_rouge;
        private int pourcentage_vert;
        private int pourcentage_bleu;
     
        public Commande(){}
     
        public Commande(String date, String heure, int pourcentage_rouge, int pourcentage_vert, int pourcentage_bleu){
            this.date = date;
            this.heure = heure;
            this.pourcentage_rouge = pourcentage_rouge;
            this.pourcentage_vert = pourcentage_vert;
            this.pourcentage_bleu = pourcentage_bleu;
        }
     
        public int getId() {
            return id;
        }
     
        public void setId(int id) {
            this.id = id;
        }
     
        public String getDate() {
            return date;
        }
     
        public void setDate(String date) {
            this.date = date;
        }
     
        public String getHeure() {
            return heure;
        }
     
        public void setHeure(String heure) {
            this.heure = heure;
        }
     
        public int getPourcentage_rouge() {
            return pourcentage_rouge;
        }
     
        public void setPoucentage_rouge(int pourcentage_rouge) {
            this.pourcentage_rouge = pourcentage_rouge;
        }
     
        public int getPourcentage_vert() {
            return pourcentage_vert;
        }
     
        public void setPourcentage_vert(int pourcentage_vert) {
            this.pourcentage_vert = pourcentage_vert;
        }
     
        public int getPourcentage_bleu() {
            return pourcentage_bleu;
        }
     
        public void setPourcentage_bleu(int pourcentage_bleu) {
            this.pourcentage_bleu = pourcentage_bleu;
        }
     
    }
    Ensuite la classe CommandesBDD :
    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
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
     
    public class CommandesBDD {
     
        private static final int VERSION_BDD = 1;
        private static final String NOM_BDD = "eleves.db";
     
        private static final String TABLE_COMMANDES = "table_commandes";
        private static final String COL_ID = "ID";
        private static final int NUM_COL_ID = 0;
        private static final String COL_DATE = "Date";
        private static final int NUM_COL_ISBN = 1;
        private static final String COL_HEURE = "Heure";
        private static final int NUM_COL_TITRE = 2;
        private static final String COL_POURCENTAGE_ROUGE = "% Rouge";
        private static final int NUM_COL_POURCENTAGE_ROUGE = 3;
        private static final String COL_POURCENTAGE_BLEU = "% Bleu";
        private static final int NUM_COL_POURCENTAGE_BLEU = 4;
        private static final String COL_POURCENTAGE_VERT = "% Vert";
        private static final int NUM_COL_POURCENTAGE_VERT = 5;
     
        private SQLiteDatabase bdd;
     
        private MaBaseSQLite maBaseSQLite;
     
        public CommandesBDD(Context context){
            //On créer la BDD et sa table
            maBaseSQLite = new MaBaseSQLite(context, NOM_BDD, null, VERSION_BDD);
        }
     
        public void open(){
            //on ouvre la BDD en écriture
            bdd = maBaseSQLite.getWritableDatabase();
        }
     
        public void close(){
            //on ferme l'accès à la BDD
            bdd.close();
        }
     
        public SQLiteDatabase getBDD(){
            return bdd;
        }
     
        public long insertCommande(Commande Commande){
            //Création d'un ContentValues (fonctionne comme une HashMap)
            ContentValues values = new ContentValues();
            //on lui ajoute une valeur associé à une clé (qui est le nom de la colonne dans laquelle on veut mettre la valeur)
            values.put(COL_DATE, Commande.getDate());
            values.put(COL_HEURE, Commande.getHeure());
            values.put(COL_POURCENTAGE_ROUGE, Commande.getPourcentage_rouge());
            values.put(COL_POURCENTAGE_BLEU, Commande.getPourcentage_bleu());
            values.put(COL_POURCENTAGE_VERT, Commande.getPourcentage_vert());
            //on insère l'objet dans la BDD via le ContentValues
            return bdd.insert(TABLE_COMMANDES, null, values);
        }
     
        public int updateCommande(int id, Commande Commande){
            //La mise à jour d'une commande dans la BDD fonctionne plus ou moins comme une insertion
            //il faut simple préciser quelle livre on doit mettre à jour grâce à l'ID
            ContentValues values = new ContentValues();
            values.put(COL_DATE, Commande.getDate());
            values.put(COL_HEURE, Commande.getHeure());
            values.put(COL_POURCENTAGE_ROUGE, Commande.getPourcentage_rouge());
            values.put(COL_POURCENTAGE_BLEU, Commande.getPourcentage_bleu());
            values.put(COL_POURCENTAGE_VERT, Commande.getPourcentage_vert());
            return bdd.update(TABLE_COMMANDES, values, COL_ID + " = " +id, null);
        }
     
        public int removeCommandeWithID(int id){
            //Suppression d'une commande de la BDD grâce à l'ID
            return bdd.delete(TABLE_COMMANDES, COL_ID + " = " +id, null);
        }
     
    }
    Et enfin la classe MaBaseSQLite :
    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
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.database.sqlite.SQLiteDatabase.CursorFactory;
     
    public class MaBaseSQLite extends SQLiteOpenHelper {
     
        private static final String TABLE_COMMANDES = "table_commandes";
        private static final String COL_ID = "ID";
        private static final String COL_DATE = "Date";
        private static final String COL_HEURE = "Heure";
        private static final String COL_POURCENTAGE_ROUGE = "Rouge";
        private static final String COL_POURCENTAGE_VERT = "Vert";
        private static final String COL_POURCENTAGE_BLEU = "Bleu";
     
        private static final String CREATE_BDD = "CREATE TABLE " + TABLE_COMMANDES + " ("
                + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_DATE + " TEXT NOT NULL, "
                + COL_HEURE + " TEXT NOT NULL, " + COL_POURCENTAGE_ROUGE + " TEXT NOT NULL, "
                + COL_POURCENTAGE_VERT + " TEXT NOT NULL, " + COL_POURCENTAGE_BLEU + " TEXT NOT NULL);";
     
        public MaBaseSQLite(Context context, String name, CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
     
        @Override
        public void onCreate(SQLiteDatabase db) {
            //on créé la table à partir de la requête écrite dans la variable CREATE_BDD
            db.execSQL(CREATE_BDD);
        }
     
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //On peut fait ce qu'on veut ici moi j'ai décidé de supprimer la table et de la recréer
            //comme ça lorsque je change la version les id repartent de 0
            db.execSQL("DROP TABLE " + TABLE_COMMANDES + ";");
            onCreate(db);
        }
    J'ai ensuite un layout Commander :
    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
    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
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/fond"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.wamove.Commander" >
     
        <Button
            android:id="@+id/button"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:background="@drawable/button_state"
            android:onClick="open_historique"
            android:text="@string/historique"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
        <Button
            android:id="@+id/button2"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:background="@drawable/button_state"
            android:text="@string/passer_la_commande"
            android:layout_alignParentRight="true"
            android:onClick="enregistrer_commande"
            android:layout_alignParentBottom="true" />
     
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:layout_above="@+id/button">
     
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="@string/passez_commande"
                android:id="@+id/textView"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:textStyle="bold|italic"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp" />
     
            <LinearLayout
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/layout"
                android:background="@drawable/layout_border"
                android:gravity="left"
                android:paddingTop="15dp"
                android:paddingBottom="15dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp">
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:gravity="center">
     
                    <TextView
                        android:layout_width="200dp"
                        android:layout_height="wrap_content"
                        android:text="@string/ndr_de_pots"
                        android:id="@+id/textView6"
                        android:textSize="25sp"
                        android:layout_marginRight="5dp"
                        android:gravity="right" />
     
                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:ems="10"
                        android:id="@+id/nbr_pots"
                        android:layout_gravity="center_horizontal"
                        android:hint="@string/max_pots"
                        android:gravity="center"
                        android:padding="0dp" />
                </LinearLayout>
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:gravity="center"
                    android:layout_marginTop="20dp">
     
                    <TextView
                        android:layout_width="200dp"
                        android:layout_height="wrap_content"
                        android:text="@string/pourc_rouge"
                        android:id="@+id/textView8"
                        android:textSize="25sp"
                        android:layout_marginRight="5dp"
                        android:gravity="right" />
     
                    <EditText
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:ems="10"
                        android:id="@+id/pourcentage_rouge"
                        android:gravity="center" />
                </LinearLayout>
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:gravity="center">
     
                    <TextView
                        android:layout_width="200dp"
                        android:layout_height="wrap_content"
                        android:text="@string/pourc_bleu"
                        android:id="@+id/textView9"
                        android:textSize="25sp"
                        android:gravity="right"
                        android:layout_marginRight="5dp" />
     
                    <EditText
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:ems="10"
                        android:id="@+id/pourcentage_bleu"
                        android:gravity="center" />
                </LinearLayout>
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:gravity="center">
     
                    <TextView
                        android:layout_width="200dp"
                        android:layout_height="wrap_content"
                        android:text="@string/pourc_vert"
                        android:id="@+id/textView10"
                        android:textSize="25sp"
                        android:layout_marginRight="5dp"
                        android:gravity="right" />
     
                    <EditText
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:ems="10"
                        android:id="@+id/pourcentage_vert"
                        android:gravity="center" />
                </LinearLayout>
     
            </LinearLayout>
        </LinearLayout>
     
    </RelativeLayout>
    Avec son code Java :
    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
    92
    package com.example.wamove;
     
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.KeyEvent;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;
    import java.util.Calendar;
     
     
     
     
     
     
    public class Commander extends Activity {
     
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_commander);
     
     
        }
     
        public void open_historique(View v){
            Intent open_historique=new Intent(Commander.this,Historique.class);
            startActivity(open_historique);
            Commander.this.finish();
        }
     
        public boolean onKeyDown(int keyCode, KeyEvent event)
        {
            //replaces the default 'Back' button action
            if(keyCode==KeyEvent.KEYCODE_BACK)
            {
                Intent open_accueil=new Intent(Commander.this,Accueil.class);
                startActivity(open_accueil);
                Commander.this.finish();
            }
            return true;
        }
     
        public void enregistrer_commande(View v){
     
            EditText nbr_pots = (EditText) findViewById(R.id.nbr_pots);
            EditText edit_pourcentage_rouge = (EditText) findViewById(R.id.pourcentage_rouge);
            EditText edit_pourcentage_vert = (EditText) findViewById(R.id.pourcentage_vert);
            EditText edit_pourcentage_bleu = (EditText) findViewById(R.id.pourcentage_bleu);
     
            if (nbr_pots.getText().toString().trim().isEmpty() || edit_pourcentage_rouge.getText().toString().trim().isEmpty() ||
                    edit_pourcentage_vert.getText().toString().trim().isEmpty() || edit_pourcentage_bleu.getText().toString().trim().isEmpty())
            {
                Toast.makeText(getApplicationContext(), "Veuillez renseigner tous les champs !",Toast.LENGTH_SHORT).show();
            }
            else
            {
                int valrouge = (int) Integer.parseInt(edit_pourcentage_rouge.getText().toString());
                int valbleu = (int) Integer.parseInt(edit_pourcentage_bleu.getText().toString());
                int valvert = (int) Integer.parseInt(edit_pourcentage_vert.getText().toString());
                if((valrouge+valbleu+valvert)!=(int)100)
                {
                    Toast.makeText(getApplicationContext(), "Le total doit être de 100% !",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    //Création d'une instance de ma classe CommandesBDD
                    CommandesBDD commandesBdd = new CommandesBDD(this);
     
                    //Création d'une commande
                    Commande commande = new Commande(String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)), String.valueOf(Calendar.getInstance().get(Calendar.DATE)),
                            valrouge, valvert, valbleu);
     
                    //On ouvre la base de données pour écrire dedans
                    commandesBdd.open();
     
                    //Toast.makeText(getApplicationContext(), "OK",Toast.LENGTH_SHORT).show();
     
                    //On insère la commande que l'on vient de créer
                    commandesBdd.insertCommande(commande);
     
                    commandesBdd.close();
     
     
     
                }
            }
     
        }
    }
    Donc, lorsque je renseigne bien tous les champs, et que la somme des 3 % vaut 100, je travaille sur la Bdd. Je n'ai aucune erreur lors de l'exécution de mon code, mais j'aimerais avoir un moyen de vérifier le contenu de ma Bdd.

    Merci d'avance !

  5. #5
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    149
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 149
    Points : 59
    Points
    59
    Par défaut
    J'ai réalisé des mis à jours de mon code.
    Commande.java :
    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
    package com.example.wamove;
     
    /**
     * Created by Oier on 10/01/2015.
     */
    public class Commande {
     
        private int id;
        private String date;
        private String heure;
        private int nbr_pots;
        private int pourcentage_rouge;
        private int pourcentage_vert;
        private int pourcentage_bleu;
     
        public Commande(){}
     
        public Commande(String date, String heure,int nbr_pots, int pourcentage_rouge, int pourcentage_vert, int pourcentage_bleu){
            this.date = date;
            this.heure = heure;
            this.nbr_pots = nbr_pots;
            this.pourcentage_rouge = pourcentage_rouge;
            this.pourcentage_vert = pourcentage_vert;
            this.pourcentage_bleu = pourcentage_bleu;
        }
     
        public int getId() {
            return id;
        }
     
        public void setId(int id) {
            this.id = id;
        }
     
        public String getDate() {
            return date;
        }
     
        public void setDate(String date) {
            this.date = date;
        }
     
        public String getHeure() {
            return heure;
        }
     
        public void setHeure(String heure) {
            this.heure = heure;
        }
     
        public int getNbr_pots() {
            return nbr_pots;
        }
     
        public void setNbr_pots(int nbr_pots) {
            this.nbr_pots = nbr_pots;
        }
     
        public int getPourcentage_rouge() {
            return pourcentage_rouge;
        }
     
        public void setPoucentage_rouge(int pourcentage_rouge) {
            this.pourcentage_rouge = pourcentage_rouge;
        }
     
        public int getPourcentage_vert() {
            return pourcentage_vert;
        }
     
        public void setPourcentage_vert(int pourcentage_vert) {
            this.pourcentage_vert = pourcentage_vert;
        }
     
        public int getPourcentage_bleu() {
            return pourcentage_bleu;
        }
     
        public void setPourcentage_bleu(int pourcentage_bleu) {
            this.pourcentage_bleu = pourcentage_bleu;
        }
     
    }
    CommandesBDD.java :
    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
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    package com.example.wamove; /**
     * Created by Oier on 10/01/2015.
     */
     
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
     
    public class CommandesBDD {
     
        private static final int VERSION_BDD = 1;
        private static final String NOM_BDD = "commandes.db";
     
        private static final String TABLE_COMMANDES = "table_commandes";
        private static final String COL_ID = "ID";
        private static final int NUM_COL_ID = 0;
        private static final String COL_DATE = "Date";
        private static final int NUM_COL_DATE = 1;
        private static final String COL_HEURE = "Heure";
        private static final int NUM_COL_HEURE = 2;
        private static final String COL_NBR_POTS = "Nbr_pots";
        private static final int NUM_COL_NBR_POTS = 3;
        private static final String COL_POURCENTAGE_ROUGE = "Rouge";
        private static final int NUM_COL_POURCENTAGE_ROUGE = 4;
        private static final String COL_POURCENTAGE_BLEU = "Bleu";
        private static final int NUM_COL_POURCENTAGE_BLEU = 5;
        private static final String COL_POURCENTAGE_VERT = "Vert";
        private static final int NUM_COL_POURCENTAGE_VERT = 6;
     
        private SQLiteDatabase bdd;
     
        private MaBaseSQLite maBaseSQLite;
     
        public CommandesBDD(Context context){
            //On créer la BDD et sa table
            maBaseSQLite = new MaBaseSQLite(context, NOM_BDD, null, VERSION_BDD);
        }
     
        public void open(){
            //on ouvre la BDD en écriture
            bdd = maBaseSQLite.getWritableDatabase();
        }
     
        public void close(){
            //on ferme l'accès à la BDD
            bdd.close();
        }
     
        public SQLiteDatabase getBDD(){
            return bdd;
        }
     
        public long insertCommande(Commande Commande){
            //Création d'un ContentValues (fonctionne comme une HashMap)
            ContentValues values = new ContentValues();
            //on lui ajoute une valeur associé à une clé (qui est le nom de la colonne dans laquelle on veut mettre la valeur)
            values.put(COL_DATE, Commande.getDate());
            values.put(COL_HEURE, Commande.getHeure());
            values.put(COL_NBR_POTS, Commande.getNbr_pots());
            values.put(COL_POURCENTAGE_ROUGE, Commande.getPourcentage_rouge());
            values.put(COL_POURCENTAGE_BLEU, Commande.getPourcentage_bleu());
            values.put(COL_POURCENTAGE_VERT, Commande.getPourcentage_vert());
            //on insère l'objet dans la BDD via le ContentValues
            return bdd.insert(TABLE_COMMANDES, null, values);
        }
     
        public int updateCommande(int id, Commande Commande){
            //La mise à jour d'une commande dans la BDD fonctionne plus ou moins comme une insertion
            //il faut simple préciser quelle livre on doit mettre à jour grâce à l'ID
            ContentValues values = new ContentValues();
            values.put(COL_DATE, Commande.getDate());
            values.put(COL_HEURE, Commande.getHeure());
            values.put(COL_NBR_POTS, Commande.getNbr_pots());
            values.put(COL_POURCENTAGE_ROUGE, Commande.getPourcentage_rouge());
            values.put(COL_POURCENTAGE_BLEU, Commande.getPourcentage_bleu());
            values.put(COL_POURCENTAGE_VERT, Commande.getPourcentage_vert());
            return bdd.update(TABLE_COMMANDES, values, COL_ID + " = " +id, null);
        }
     
        public int removeCommandeWithID(int id){
            //Suppression d'une commande de la BDD grâce à l'ID
            return bdd.delete(TABLE_COMMANDES, COL_ID + " = " +id, null);
        }
     
        //Cette méthode permet de convertir un cursor en une commande
        private Commande cursorToLivre(Cursor c){
            //si aucun élément n'a été retourné dans la requête, on renvoie null
            if (c.getCount() == 0)
                return null;
     
            //Sinon on se place sur le premier élément
            c.moveToFirst();
            //On créé une commande
            Commande commande = new Commande();
            //on lui affecte toutes les infos grâce aux infos contenues dans le Cursor
            commande.setId(c.getInt(NUM_COL_ID));
            commande.setDate(c.getString(NUM_COL_DATE));
            commande.setHeure(c.getString(NUM_COL_HEURE));
            commande.setNbr_pots(c.getInt(NUM_COL_NBR_POTS));
            commande.setPoucentage_rouge(c.getInt(NUM_COL_POURCENTAGE_ROUGE));
            commande.setPourcentage_bleu(c.getInt(NUM_COL_POURCENTAGE_BLEU));
            commande.setPourcentage_vert(c.getInt(NUM_COL_POURCENTAGE_VERT));
            //On ferme le cursor
            c.close();
     
            //On retourne la commande
            return commande;
        }
     
    }
    MaBaseSQLite.java :
    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
    package com.example.wamove; /**
     * Created by Oier on 10/01/2015.
     */
     
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteDatabase.CursorFactory;
    import android.database.sqlite.SQLiteOpenHelper;
     
    public class MaBaseSQLite extends SQLiteOpenHelper {
     
        private static final String TABLE_COMMANDES = "table_commandes";
        private static final String COL_ID = "ID";
        private static final String COL_DATE = "Date";
        private static final String COL_HEURE = "Heure";
        private static final String COL_NBR_POTS = "Nbr_pots";
        private static final String COL_POURCENTAGE_ROUGE = "Rouge";
        private static final String COL_POURCENTAGE_VERT = "Vert";
        private static final String COL_POURCENTAGE_BLEU = "Bleu";
     
        private static final String CREATE_BDD = "CREATE TABLE " + TABLE_COMMANDES + " ("
                + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_DATE + " TEXT NOT NULL, "
                + COL_HEURE + " TEXT NOT NULL, " + COL_NBR_POTS + " TEXT NOT NULL, " + COL_POURCENTAGE_ROUGE
                + " TEXT NOT NULL, " + COL_POURCENTAGE_VERT + " TEXT NOT NULL, " + COL_POURCENTAGE_BLEU + " TEXT NOT NULL);";
     
        public MaBaseSQLite(Context context, String name, CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
     
        @Override
        public void onCreate(SQLiteDatabase db) {
            //on créé la table à partir de la requête écrite dans la variable CREATE_BDD
            db.execSQL(CREATE_BDD);
        }
     
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //On peut fait ce qu'on veut ici moi j'ai décidé de supprimer la table et de la recréer
            //comme ça lorsque je change la version les id repartent de 0
            db.execSQL("DROP TABLE " + TABLE_COMMANDES + ";");
            onCreate(db);
        }
     
    }
    Layout Commander:
    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
    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
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/fond"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.wamove.Commander" >
     
        <Button
            android:id="@+id/button"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:background="@drawable/button_state"
            android:onClick="open_historique"
            android:text="@string/historique"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
        <Button
            android:id="@+id/button2"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:background="@drawable/button_state"
            android:text="@string/passer_la_commande"
            android:layout_alignParentRight="true"
            android:onClick="enregistrer_commande"
            android:layout_alignParentBottom="true" />
     
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:layout_above="@+id/button">
     
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="@string/passez_commande"
                android:id="@+id/textView"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:textStyle="bold|italic"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp" />
     
            <LinearLayout
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/layout"
                android:background="@drawable/layout_border"
                android:gravity="left"
                android:paddingTop="15dp"
                android:paddingBottom="15dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp">
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center_horizontal"
                    android:gravity="center">
     
                    <TextView
                        android:layout_width="200dp"
                        android:layout_height="wrap_content"
                        android:text="@string/ndr_de_pots"
                        android:id="@+id/textView6"
                        android:textSize="25sp"
                        android:layout_marginRight="5dp"
                        android:gravity="right" />
     
                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:ems="10"
                        android:id="@+id/nbr_pots"
                        android:layout_gravity="center_horizontal"
                        android:hint="@string/max_pots"
                        android:gravity="center"
                        android:padding="0dp" />
                </LinearLayout>
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:gravity="center"
                    android:layout_marginTop="20dp">
     
                    <TextView
                        android:layout_width="200dp"
                        android:layout_height="wrap_content"
                        android:text="@string/pourc_rouge"
                        android:id="@+id/textView8"
                        android:textSize="25sp"
                        android:layout_marginRight="5dp"
                        android:gravity="right" />
     
                    <EditText
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:ems="10"
                        android:id="@+id/pourcentage_rouge"
                        android:gravity="center" />
                </LinearLayout>
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:gravity="center">
     
                    <TextView
                        android:layout_width="200dp"
                        android:layout_height="wrap_content"
                        android:text="@string/pourc_bleu"
                        android:id="@+id/textView9"
                        android:textSize="25sp"
                        android:gravity="right"
                        android:layout_marginRight="5dp" />
     
                    <EditText
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:ems="10"
                        android:id="@+id/pourcentage_bleu"
                        android:gravity="center" />
                </LinearLayout>
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:gravity="center">
     
                    <TextView
                        android:layout_width="200dp"
                        android:layout_height="wrap_content"
                        android:text="@string/pourc_vert"
                        android:id="@+id/textView10"
                        android:textSize="25sp"
                        android:layout_marginRight="5dp"
                        android:gravity="right" />
     
                    <EditText
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:ems="10"
                        android:id="@+id/pourcentage_vert"
                        android:gravity="center" />
                </LinearLayout>
     
            </LinearLayout>
        </LinearLayout>
     
    </RelativeLayout>
    Commander.java :
    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
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    package com.example.wamove;
     
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.KeyEvent;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;
     
    import java.util.Calendar;
     
    public class Commander extends Activity {
     
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_commander);
     
     
        }
     
        public void open_historique(View v){
            Intent open_historique=new Intent(Commander.this,Historique.class);
            startActivity(open_historique);
            Commander.this.finish();
        }
     
        public boolean onKeyDown(int keyCode, KeyEvent event)
        {
            //replaces the default 'Back' button action
            if(keyCode==KeyEvent.KEYCODE_BACK)
            {
                Intent open_accueil=new Intent(Commander.this,Accueil.class);
                startActivity(open_accueil);
                Commander.this.finish();
            }
            return true;
        }
     
        public void enregistrer_commande(View v){
     
            EditText nbr_pots = (EditText) findViewById(R.id.nbr_pots);
            EditText edit_pourcentage_rouge = (EditText) findViewById(R.id.pourcentage_rouge);
            EditText edit_pourcentage_vert = (EditText) findViewById(R.id.pourcentage_vert);
            EditText edit_pourcentage_bleu = (EditText) findViewById(R.id.pourcentage_bleu);
     
            if (nbr_pots.getText().toString().trim().isEmpty() || edit_pourcentage_rouge.getText().toString().trim().isEmpty() ||
                    edit_pourcentage_vert.getText().toString().trim().isEmpty() || edit_pourcentage_bleu.getText().toString().trim().isEmpty())
            {
                Toast.makeText(getApplicationContext(), "Veuillez renseigner tous les champs !",Toast.LENGTH_SHORT).show();
            }
            else
            {
                int nbrpots = (int) Integer.parseInt(nbr_pots.getText().toString());
                int valrouge = (int) Integer.parseInt(edit_pourcentage_rouge.getText().toString());
                int valbleu = (int) Integer.parseInt(edit_pourcentage_bleu.getText().toString());
                int valvert = (int) Integer.parseInt(edit_pourcentage_vert.getText().toString());
     
                if( nbrpots > (int) 20)
                {
                    Toast.makeText(getApplicationContext(), "20 pots maximum !", Toast.LENGTH_SHORT).show();
                }
                else if (nbrpots==0)
                {
                    Toast.makeText(getApplicationContext(), "Au moins 1 pot !", Toast.LENGTH_SHORT).show();
                }
                else {
                    if ((valrouge + valbleu + valvert) != 100)
                    {
                        Toast.makeText(getApplicationContext(), "Le total doit être de 100% !", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        //Création d'une instance de ma classe CommandesBDD
                        CommandesBDD commandesBdd = new CommandesBDD(this);
     
                        //Création d'une commande
                        Commande commande = new Commande( String.valueOf(Calendar.getInstance().get(Calendar.DATE)+"/"+Calendar.getInstance().get(Calendar.MONTH)+"/"+Calendar.getInstance().get(Calendar.YEAR)),String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE)),
                                nbrpots, valrouge, valvert, valbleu);
     
                        //On ouvre la base de données pour écrire dedans
                        commandesBdd.open();
     
                        //Toast.makeText(getApplicationContext(), "OK",Toast.LENGTH_SHORT).show();
     
                        //On insère la commande que l'on vient de créer
                        commandesBdd.insertCommande(commande);
     
                        commandesBdd.close();
     
                        Toast.makeText(getApplicationContext(), "Commande enregistrée", Toast.LENGTH_SHORT).show();
     
                        Intent open_accueil=new Intent(Commander.this,Accueil.class);
                        startActivity(open_accueil);
                        Commander.this.finish();
                    }
                }
            }
     
        }
    }

  6. #6
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Bonjour,
    Pour la classe Commande.java, rien de grave à signaler;
    Seulement pour les deux autres classes à savoir CommandesBDD.java (classe d'accès aux données) et MaBaseSQLite.java (Classe de gestion de la base de données (création de la base, des tables, mise à jour de la structure des tables...)) il y a un tout petit peu de redondances dans les déclarations des champs.
    Ces attributs de la classe MaBaseSQLite.java suffiraient pour être appelés dans la classe CommandesBDD.java pour raison de manipulations de la table des commandes du fait qu'ils soient déclarés static:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    private static final String TABLE_COMMANDES = "table_commandes";
        private static final String COL_ID = "ID";
        private static final String COL_DATE = "Date";
        private static final String COL_HEURE = "Heure";
        private static final String COL_NBR_POTS = "Nbr_pots";
        private static final String COL_POURCENTAGE_ROUGE = "Rouge";
        private static final String COL_POURCENTAGE_VERT = "Vert";
        private static final String COL_POURCENTAGE_BLEU = "Bleu";

    Sinon, tu es dans la logique je peux dire sauf que tu n'as pas géré les cas d'exceptions (try); Exécute d'abord est fais signe.

  7. #7
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    149
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 149
    Points : 59
    Points
    59
    Par défaut
    Tout d'abord merci beaucoup pour ta réponse.

    Concernant la déclaration des champs, je vois bien qu'il y a de la redondance, mais comment y pallier ?
    Sinon question bête mais lorsque j'appuie la première fois sur le bouton, les données sont bien enregistrées, mais si j'appuie une deuxième fois, les premières données ne sont pas supprimées au moins ? En gros est-ce que le code que j'ai est correct dans l'ensemble ? Comment pourrais-je, par exemple, récupérer le nombre d'éléments présents dans la bdd afin de l'afficher via un Toast.

    Je suis aussi en train de voir pour afficher le contenu de ma bdd dans une ListView suite à ton conseil, mais pour cela il faut que je trouve les requêtes à effectuer afin de récupérer les données, c'est bien ça ?

    Merci beaucoup en tout cas

  8. #8
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    149
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 149
    Points : 59
    Points
    59
    Par défaut
    Re

    Je viens de trouver sur le net une application que utilise aussi une base de donnée, mais de manière beaucoup plus simple il me semble.
    MyApp.Java :
    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
    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
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    package com.azim;
     
    import android.app.Activity;
    import android.app.AlertDialog.Builder;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
     
    public class MyApp extends Activity implements OnClickListener
    {
    	EditText editRollno,editName,editMarks;
    	Button btnAdd,btnDelete,btnModify,btnView,btnViewAll,btnShowInfo;
    	SQLiteDatabase db;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            editRollno=(EditText)findViewById(R.id.editRollno);
            editName=(EditText)findViewById(R.id.editName);
            editMarks=(EditText)findViewById(R.id.editMarks);
            btnAdd=(Button)findViewById(R.id.btnAdd);
            btnDelete=(Button)findViewById(R.id.btnDelete);
            btnModify=(Button)findViewById(R.id.btnModify);
            btnView=(Button)findViewById(R.id.btnView);
            btnViewAll=(Button)findViewById(R.id.btnViewAll);
            btnShowInfo=(Button)findViewById(R.id.btnShowInfo);
            btnAdd.setOnClickListener(this);
            btnDelete.setOnClickListener(this);
            btnModify.setOnClickListener(this);
            btnView.setOnClickListener(this);
            btnViewAll.setOnClickListener(this);
            btnShowInfo.setOnClickListener(this);
            db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
    		db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks VARCHAR);");
        }
        public void onClick(View view)
        {
        	if(view==btnAdd)
        	{
        		if(editRollno.getText().toString().trim().length()==0||
        		   editName.getText().toString().trim().length()==0||
        		   editMarks.getText().toString().trim().length()==0)
        		{
        			showMessage("Error", "Please enter all values");
        			return;
        		}
        		db.execSQL("INSERT INTO student VALUES('"+editRollno.getText()+"','"+editName.getText()+
        				   "','"+editMarks.getText()+"');");
        		showMessage("Success", "Record added");
        		clearText();
        	}
        	if(view==btnDelete)
        	{
        		if(editRollno.getText().toString().trim().length()==0)
        		{
        			showMessage("Error", "Please enter Rollno");
        			return;
        		}
        		Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+editRollno.getText()+"'", null);
        		if(c.moveToFirst())
        		{
        			db.execSQL("DELETE FROM student WHERE rollno='"+editRollno.getText()+"'");
        			showMessage("Success", "Record Deleted");
        		}
        		else
        		{
        			showMessage("Error", "Invalid Rollno");
        		}
        		clearText();
        	}
        	if(view==btnModify)
        	{
        		if(editRollno.getText().toString().trim().length()==0)
        		{
        			showMessage("Error", "Please enter Rollno");
        			return;
        		}
        		Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+editRollno.getText()+"'", null);
        		if(c.moveToFirst())
        		{
        			db.execSQL("UPDATE student SET name='"+editName.getText()+"',marks='"+editMarks.getText()+
        					"' WHERE rollno='"+editRollno.getText()+"'");
        			showMessage("Success", "Record Modified");
        		}
        		else
        		{
        			showMessage("Error", "Invalid Rollno");
        		}
        		clearText();
        	}
        	if(view==btnView)
        	{
        		if(editRollno.getText().toString().trim().length()==0)
        		{
        			showMessage("Error", "Please enter Rollno");
        			return;
        		}
        		Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+editRollno.getText()+"'", null);
        		if(c.moveToFirst())
        		{
        			editName.setText(c.getString(1));
        			editMarks.setText(c.getString(2));
        		}
        		else
        		{
        			showMessage("Error", "Invalid Rollno");
        			clearText();
        		}
        	}
        	if(view==btnViewAll)
        	{
        		Cursor c=db.rawQuery("SELECT * FROM student", null);
        		if(c.getCount()==0)
        		{
        			showMessage("Error", "No records found");
        			return;
        		}
        		StringBuffer buffer=new StringBuffer();
        		while(c.moveToNext())
        		{
        			buffer.append("Rollno: "+c.getString(0)+"\n");
        			buffer.append("Name: "+c.getString(1)+"\n");
        			buffer.append("Marks: "+c.getString(2)+"\n\n");
        		}
        		showMessage("Student Details", buffer.toString());
        	}
        	if(view==btnShowInfo)
        	{
    			showMessage("Student Management Application", "Developed By Azim");
        	}
        }
        public void showMessage(String title,String message)
        {
        	Builder builder=new Builder(this);
        	builder.setCancelable(true);
        	builder.setTitle(title);
        	builder.setMessage(message);
        	builder.show();
    	}
        public void clearText()
        {
        	editRollno.setText("");
        	editName.setText("");
        	editMarks.setText("");
        	editRollno.requestFocus();
        }
    }
    et Main.xml :
    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
    <?xml version="1.0" encoding="utf-8"?>
    <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
                 android:id="@+id/myLayout"
                 android:stretchColumns="0"
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent">
    		<TextView android:text="@string/title"
    				  android:layout_x="110dp"
    				  android:layout_y="10dp"
    		          android:layout_width="wrap_content"
    		          android:layout_height="wrap_content"/>
    		<TextView android:text="@string/roll_no"
    				  android:layout_x="30dp"
    				  android:layout_y="50dp"
    		          android:layout_width="wrap_content"
    		          android:layout_height="wrap_content"/>
    		<EditText android:id="@+id/editRollno"
    				  android:inputType="number"	 
    				  android:layout_x="150dp"
    				  android:layout_y="50dp"
    		          android:layout_width="150dp"
    		          android:layout_height="40dp"/>
    		<TextView android:text="@string/name"
    				  android:layout_x="30dp"
    				  android:layout_y="100dp"
    		          android:layout_width="wrap_content"
    		          android:layout_height="wrap_content"/>
    		<EditText android:id="@+id/editName"	 
    				  android:inputType="text"	 
    				  android:layout_x="150dp"
    				  android:layout_y="100dp"
    		          android:layout_width="150dp"
    		          android:layout_height="40dp"/>
    		<TextView android:text="@string/marks"
    				  android:layout_x="30dp"
    				  android:layout_y="150dp"
    		          android:layout_width="wrap_content"
    		          android:layout_height="wrap_content"/>
    		<EditText android:id="@+id/editMarks"	 
    				  android:inputType="number"	 
    				  android:layout_x="150dp"
    				  android:layout_y="150dp"
    		          android:layout_width="150dp"
    		          android:layout_height="40dp"/>
    		<Button	  android:id="@+id/btnAdd"
    				  android:text="@string/add"
    				  android:layout_x="30dp"
    				  android:layout_y="200dp"
    		          android:layout_width="100dp"
    		          android:layout_height="40dp"/>
    		<Button	  android:id="@+id/btnDelete"
    				  android:text="@string/delete"
    				  android:layout_x="150dp"
    				  android:layout_y="200dp"
    		          android:layout_width="100dp"
    		          android:layout_height="40dp"/>n
    		<Button   android:id="@+id/btnModify"
    				  android:text="@string/modify"
    				  android:layout_x="30dp"
    				  android:layout_y="250dp"
    		          android:layout_width="100dp"
    		          android:layout_height="40dp"/>
    		<Button   android:id="@+id/btnView"
    				  android:text="@string/view"
    				  android:layout_x="150dp"
    				  android:layout_y="250dp"
    		          android:layout_width="100dp"
    		          android:layout_height="40dp"/>
    		<Button   android:id="@+id/btnViewAll"
    				  android:text="@string/view_all"
    				  android:layout_x="30dp"
    				  android:layout_y="300dp"
    		          android:layout_width="100dp"
    		          android:layout_height="40dp"/>
    		<Button   android:id="@+id/btnShowInfo"
    				  android:text="@string/show_info"
    				  android:layout_x="150dp"
    				  android:layout_y="300dp"
    		          android:layout_width="100dp"
    		          android:layout_height="40dp"/>
    </AbsoluteLayout>
    N'est-ce pas plus simple que je fasse comme ça aussi ?

  9. #9
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Citation Envoyé par oieretxe Voir le message
    Tout d'abord merci beaucoup pour ta réponse.
    Je t'en prie...
    Citation Envoyé par oieretxe Voir le message
    Concernant la déclaration des champs, je vois bien qu'il y a de la redondance, mais comment y pallier ?
    Comme j'avais dit, du fait que tu les aies déclarées static dans la classe MaBaseSQLite.java, cela te permet d'accéder à chaque membre juste par un appel du genre MaBaseSQLite.nomDuchamp dans la classe CommandesBDD.java. Par exemple, pour faire référence au champ COL_ID dans la classe CommandesBDD.java il suffit de taper MaBaseSQLite.COL_ID... Dans le code tu aurais :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    public long insertCommande(Commande Commande){
            //Création d'un ContentValues (fonctionne comme une HashMap)
            ContentValues values = new ContentValues();
            //on lui ajoute une valeur associé à une clé (qui est le nom de la colonne dans laquelle on veut mettre la valeur)
            values.put(MaBaseSQLite.COL_DATE, Commande.getDate());
            values.put(MaBaseSQLite.COL_HEURE, Commande.getHeure());
            values.put(MaBaseSQLite.COL_NBR_POTS, Commande.getNbr_pots());
            values.put(MaBaseSQLite.COL_POURCENTAGE_ROUGE, Commande.getPourcentage_rouge());
            values.put(MaBaseSQLite.COL_POURCENTAGE_BLEU, Commande.getPourcentage_bleu());
            values.put(MaBaseSQLite.COL_POURCENTAGE_VERT, Commande.getPourcentage_vert());
            //on insère l'objet dans la BDD via le ContentValues
            return bdd.insert(MaBaseSQLite.TABLE_COMMANDES, null, values);
        }
    Citation Envoyé par oieretxe Voir le message
    Sinon question bête mais lorsque j'appuie la première fois sur le bouton, les données sont bien enregistrées, mais si j'appuie une deuxième fois, les premières données ne sont pas supprimées au moins ?
    Non, les premières données ne seront pas supprimées d'autant plus que la colonne servant de clé primaire s'incrémente automatiquement à chaque insertion dans la table. Même si tu enregistre les mêmes informations que précédemment, à cause de l'auto-incrémentation de la clé primaire cela sera vu comme une nouvelle donnée.

    Citation Envoyé par oieretxe Voir le message
    En gros est-ce que le code que j'ai est correct dans l'ensemble ?
    En gros oui, mais pas en détail parce que tu n'as pas géré les erreurs qui pourraient faire cracher ton application mais aussi ta classe CommandesBDD.java n'est pas bien peuplée par des méthodes...

    Citation Envoyé par oieretxe Voir le message
    Comment pourrais-je, par exemple, récupérer le nombre d'éléments présents dans la bdd afin de l'afficher via un Toast.
    La classe Cursor dispose d'une méthode getCount() qui envoie le nombre de lignes contenues dans un objet Cursor. Tu peux l'utiliser dans une méthode que tu ajoutes dans la classe CommandesBDD.java comme suit :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    public int nombreDeLigne(){
      //sélectionner toutes les lignes de la table commandes
      Cursor curseur = db.query(MaBaseSQLite.TABLE_COMMANDES, null, null, null, null, null, null);
      //Renvoyer le nombre de lignes
      return curseur.getCount();
    }
    Citation Envoyé par oieretxe Voir le message
    Je suis aussi en train de voir pour afficher le contenu de ma bdd dans une ListView suite à ton conseil, mais pour cela il faut que je trouve les requêtes à effectuer afin de récupérer les données, c'est bien ça ?
    Oui c'est ça! ajoute une autre méthode dans la classe CommandesBDD.java qui va te renvoyer toutes les données contenues dans la table Commandes de ta Base de données. Cette méthode doit renvoyer une ArrayList de commandes.

  10. #10
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    149
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 149
    Points : 59
    Points
    59
    Par défaut
    J'ai essayé la méthode nombreDeLigne() mais j'ai l'application qui crash lorsque je l'appelle en faisant :
    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
    //Création d'une instance de ma classe CommandesBDD
                        CommandesBDD commandesBdd = new CommandesBDD(this);
     
                        //Création d'une commande
                        Commande commande = new Commande( String.valueOf(Calendar.getInstance().get(Calendar.DATE)+"/"+Calendar.getInstance().get(Calendar.MONTH)+"/"+Calendar.getInstance().get(Calendar.YEAR)),String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE)),
                                nbrpots, valrouge, valvert, valbleu);
     
                        //On ouvre la base de données pour écrire dedans
                        commandesBdd.open();
     
                        //Toast.makeText(getApplicationContext(), "OK",Toast.LENGTH_SHORT).show();
     
                        //On insère la commande que l'on vient de créer
                        commandesBdd.insertCommande(commande);
     
                        commandesBdd.close();
     
                        Toast.makeText(getApplicationContext(), "Commande enregistrée", Toast.LENGTH_SHORT).show();
     
                        Intent open_accueil=new Intent(Commander.this,Accueil.class);
     
                        Toast.makeText(getApplicationContext(), "Il y a maintenant "+commandesBdd.nombreDeLigne()+" éléments dans la Bdd", Toast.LENGTH_SHORT).show();
    D'un autre coté, j'ai commencé à travailler sur la méthode me renvoyant une ArrayList, mais l'application crash aussi lorsque je l'appelle... voici le code, mis dans CommandesBDD.java :
    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
    public ArrayList<HashMap<String, String>>  getCommandesList() {
     
            SQLiteDatabase db = maBaseSQLite.getReadableDatabase();
            String selectQuery =  "SELECT  " +
                    NUM_COL_ID + "," +
                    NUM_COL_DATE + "," +
                    NUM_COL_HEURE + "," +
                    NUM_COL_NBR_POTS + "," +
                    NUM_COL_POURCENTAGE_ROUGE + "," +
                    NUM_COL_POURCENTAGE_BLEU + "," +
                    NUM_COL_POURCENTAGE_VERT +
                    " FROM " + MaBaseSQLite.TABLE_COMMANDES;
     
            ArrayList<HashMap<String, String>> commandesList = new ArrayList<HashMap<String, String>>();
     
            Cursor cursor = db.rawQuery(selectQuery, null);
     
            if (cursor.moveToFirst()) {
                do {
                    HashMap<String, String> commande = new HashMap<String, String>();
                    commande.put("ID", cursor.getString(cursor.getColumnIndex(MaBaseSQLite.COL_ID)));
                    commande.put("Date", cursor.getString(cursor.getColumnIndex(MaBaseSQLite.COL_DATE)));
                    commande.put("Heure", cursor.getString(cursor.getColumnIndex(MaBaseSQLite.COL_HEURE)));
                    commande.put("Nbr_pots", cursor.getString(cursor.getColumnIndex(MaBaseSQLite.COL_NBR_POTS)));
                    commande.put("Rouge", cursor.getString(cursor.getColumnIndex(MaBaseSQLite.COL_POURCENTAGE_ROUGE)));
                    commande.put("Bleu", cursor.getString(cursor.getColumnIndex(MaBaseSQLite.COL_POURCENTAGE_BLEU)));
                    commande.put("Vert", cursor.getString(cursor.getColumnIndex(MaBaseSQLite.COL_POURCENTAGE_VERT)));
                    commandesList.add(commande);
     
                } while (cursor.moveToNext());
            }
     
            cursor.close();
            db.close();
            return commandesList;
     
        }
    J'ai pris ça d'une appli trouvée sur internet en l'arrangeant pour coller à mon appli, mais j'ai du faire une erreur

  11. #11
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Citation Envoyé par oieretxe Voir le message
    J'ai essayé la méthode nombreDeLigne() mais j'ai l'application qui crash lorsque je l'appelle en faisant :
    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
    //Création d'une instance de ma classe CommandesBDD
                        CommandesBDD commandesBdd = new CommandesBDD(this);
     
                        //Création d'une commande
                        Commande commande = new Commande( String.valueOf(Calendar.getInstance().get(Calendar.DATE)+"/"+Calendar.getInstance().get(Calendar.MONTH)+"/"+Calendar.getInstance().get(Calendar.YEAR)),String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE)),
                                nbrpots, valrouge, valvert, valbleu);
     
                        //On ouvre la base de données pour écrire dedans
                        commandesBdd.open();
     
                        //Toast.makeText(getApplicationContext(), "OK",Toast.LENGTH_SHORT).show();
     
                        //On insère la commande que l'on vient de créer
                        commandesBdd.insertCommande(commande);
     
                        commandesBdd.close();
     
                        Toast.makeText(getApplicationContext(), "Commande enregistrée", Toast.LENGTH_SHORT).show();
     
                        Intent open_accueil=new Intent(Commander.this,Accueil.class);
     
                        Toast.makeText(getApplicationContext(), "Il y a maintenant "+commandesBdd.nombreDeLigne()+" éléments dans la Bdd", Toast.LENGTH_SHORT).show();
    De première vue, je remarque que tu fermes la base de données avec avant l'appel de la méthode nombreDeLigne(). Ne sois pas pressé de fermer l'accès à la base de données si tu n'es pas sûr d'avoir fini tous les traitements. Tu peux afficher le Toast avant sans même avoir lancé une autre activity pour raison de test.

  12. #12
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    149
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 149
    Points : 59
    Points
    59
    Par défaut
    En effet, j'avais mal placé mon code. Du coup je retrouve bien le résultat attendu avec commandesBdd.nombreDeLigne() ! Merci beaucoup !

    Concernant ma méthode getCommandesList() as-tu pu y jeter un coup d’œil ? Je l'ai testé comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    ArrayList<HashMap<String, String>> commandesList =  commandesBdd.getCommandesList();
    Mais j'ai un crash, avec marqué dans Android Studio :
    14004-14004/com.example.wamove E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 2 rows,

    Je vais m'y chercher d'où ça vient, mais si tu as une idée c'est avec plaisir !

  13. #13
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Citation Envoyé par oieretxe Voir le message
    En effet, j'avais mal placé mon code. Du coup je retrouve bien le résultat attendu avec commandesBdd.nombreDeLigne() ! Merci beaucoup !
    Je t'en prie
    Citation Envoyé par oieretxe Voir le message
    Concernant ma méthode getCommandesList() as-tu pu y jeter un coup d’œil ? Je l'ai testé comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    ArrayList<HashMap<String, String>> commandesList =  commandesBdd.getCommandesList();
    Mais j'ai un crash, avec marqué dans Android Studio :
    14004-14004/com.example.wamove E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 2 rows,

    Je vais m'y chercher d'où ça vient, mais si tu as une idée c'est avec plaisir !
    Je ne vois pas trop pourquoi tu utilises ArrayList<HashMap<String, String>> pour renvoyer la liste des commandes. Sinon, un simple ArrayList<Commande> suffirait et ne serait pas trop complexe à gérer. Je vais te donner quelques indications :
    - D'abord, crée ta méthode avec cette signature
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    public ArrayList<Commande> listeDesCommandes(){
     
    }
    Là tu comprends qu'il s'agira bien sûr d'une liste des objets de ta classe Commande avec leurs attributs bien peuplés...
    - Ensuite, à l'intérieur de cette méthode tu crées une ArrayList dans laquelle, à l'issue de chaque lecture d'une ligne dans ta table, sera ajoutée cette dernière.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     ArrayList<Commande> listeDesCommandes = new  ArrayList<Commande>();
    - Pour le reste, l'explication dans le code ci-dessous :
    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
     
    //Déclarer un objet Commande qui servira de tampon
    Commande c; 
    //Exécution de la requête de sélection de toutes les lignes contenues dans la table
    Cursor curseur = db.query(MaBaseSQLite.TABLE_COMMANDES, null, null, null, null, null, null);
    //Vérifier si le curseur contient au moins une ligne
    if (curseur != null) {
    //Se placer au premier enregistrement
    curseur.moveToFirst();
    //Parcourir les enregistrement tant que le dernier n'est pas encore lu (En quelque sorte)...
    while (!curseur.isAfterLast()) {
            //Créer une commande
    	c = new Commande();
            //Affecter chaque valeur provenant d'un champ de la base de données à l'objet c
    	c.setId(curseur.getInt(curseur.getColumnIndex(MaBaseSQLite.COL_ID)));
            c.setDate(curseur.getInt(curseur.getColumnIndex(MaBaseSQLite.COL_DATE)));
            //Suis la même logique pour récupérer tous les autres champs
            //...
            //...
     
            //Ajouter la commande dans la liste				
    	listeDesCommandes.add(c);
            //Passer à l'enregistrement suivant
    	curseur.moveToNext();
    }
    //Fermer le curseur
    curseur.close();
    }
    //Retourner la liste
    return list_rapport;

  14. #14
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    149
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 149
    Points : 59
    Points
    59
    Par défaut
    Merci ça marche nickel !

    Alors maintenant lorsque je vais dans ma page où je veux afficher ma bdd, je réalise pour le moment ceci :
    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
    package com.example.wamove;
     
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import java.util.*;
     
     
    public class Historique extends Activity {
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_historique);
     
           CommandesBDD commandesBdd = new CommandesBDD(this);
     
            commandesBdd.open();
     
            ArrayList<Commande> list_rapport = new  ArrayList<Commande>();
     
            list_rapport =  commandesBdd.listeDesCommandes();
     
            commandesBdd.close();
        }
     
    }
    Et pas de crash ! ^^
    Par contre je voudrais maintenant afficher tout ça dans un ListView comme tu me l'a conseillé. Je voudrais afficher une sorte de tableau, qui contiendra tous les items de ma ArrayList. Si j'ai bien compris les tutos trouvés, il me faut passer par un arrayAdapter c'est ça ?

  15. #15
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Citation Envoyé par oieretxe Voir le message
    Et pas de crash ! ^^
    Heureusement pour toi
    Citation Envoyé par oieretxe Voir le message
    Par contre je voudrais maintenant afficher tout ça dans un ListView comme tu me l'a conseillé. Je voudrais afficher une sorte de tableau, qui contiendra tous les items de ma ArrayList. Si j'ai bien compris les tutos trouvés, il me faut passer par un arrayAdapter c'est ça ?
    Pour une liste d'une seule colonne, cela suffira! Mais si tu veux par contre afficher plusieurs colonnes pour une ligne donnée, il te faudra passer par un adaptateur personnalisé. Donc tu vas créer ton propre adaptateur (t'en fais pas tu ne réinventer la roue ) en créant une classe qui va hériter de la classe BaseAdapter. Ca devient un peu plus robuste dans ce cas et ça fera un peu mal au début, heureusement que deloppez.net soit là...

  16. #16
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    149
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 149
    Points : 59
    Points
    59
    Par défaut
    Bon j'ai pas mal avancé, mais j'ai quand même un crash au bout, et Android Studio ne m'indique pas d'où vient le crash du coup j'ai du mal à trouver...

    Tout d'abord j'ai légèrement modifié les noms des champs de ma Bdd, je te mets la nouvelle version :
    Lecture.java :
    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
    package com.example.wamove;
     
    /**
     * Created by Oier on 10/01/2015.
     */
    public class Lecture {
     
        private int id;
        private String type;
        private String adresse;
        private String etat;
        private String date;
        private String heure;
     
        public Lecture(){}
     
        public Lecture(String type, String adresse, String etat, String date, String heure){
            this.type = type;
            this.adresse = adresse;
            this.etat = etat;
            this.date = date;
            this.heure = heure;
        }
     
        public int getId() {
            return id;
        }
     
        public void setId(int id) {
            this.id = id;
        }
     
        public String getType() {
            return type;
        }
     
        public void setType(String type) {
            this.type = type;
        }
     
        public String getAdresse() {
            return adresse;
        }
     
        public void setAdresse(String adresse) {
            this.adresse = adresse;
        }
     
        public String getEtat() {
            return etat;
        }
     
        public void setEtat(String etat) {
            this.etat = etat;
        }
     
        public String getDate() {
            return date;
        }
     
        public void setDate(String date) {
            this.date = date;
        }
     
        public String getHeure() {
            return heure;
        }
     
        public void setHeure(String heure) {
            this.heure = heure;
        }
    }
    LectureBDD.java :
    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
    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
    package com.example.wamove; /**
     * Created by Oier on 10/01/2015.
     */
     
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import java.util.*;
     
    public class LecturesBDD {
     
        private static final int VERSION_BDD = 1;
        private static final String NOM_BDD = "lecture.db";
     
        public static final int NUM_COL_ID = 0;
        private static final int NUM_COL_TYPE = 1;
        private static final int NUM_COL_ADRESSE = 2;
        private static final int NUM_COL_ETAT = 3;
        private static final int NUM_COL_DATE = 4;
        private static final int NUM_COL_HEURE = 5;
     
        private SQLiteDatabase bdd;
     
        private MaBaseSQLite maBaseSQLite;
     
        public LecturesBDD(Context context){
            //On créer la BDD et sa table
            maBaseSQLite = new MaBaseSQLite(context, NOM_BDD, null, VERSION_BDD);
        }
     
        public void open(){
            //on ouvre la BDD en écriture
            bdd = maBaseSQLite.getWritableDatabase();
        }
     
        public void close(){
            //on ferme l'accès à la BDD
            bdd.close();
        }
     
        public SQLiteDatabase getBDD(){
            return bdd;
        }
     
        public long insertLecture(Lecture Lecture){
            //Création d'un ContentValues (fonctionne comme une HashMap)
            ContentValues values = new ContentValues();
            //on lui ajoute une valeur associé à une clé (qui est le nom de la colonne dans laquelle on veut mettre la valeur)
            values.put(MaBaseSQLite.COL_TYPE, Lecture.getType());
            values.put(MaBaseSQLite.COL_ADRESSE, Lecture.getAdresse());
            values.put(MaBaseSQLite.COL_ETAT, Lecture.getEtat());
            values.put(MaBaseSQLite.COL_DATE, Lecture.getEtat());
            values.put(MaBaseSQLite.COL_HEURE, Lecture.getEtat());
            //on insère l'objet dans la BDD via le ContentValues
            return bdd.insert(MaBaseSQLite.TABLE_LECTURES, null, values);
        }
     
        public int updateCommande(int id, Lecture Lecture){
            //La mise à jour d'une commande dans la BDD fonctionne plus ou moins comme une insertion
            //il faut simple préciser quelle livre on doit mettre à jour grâce à l'ID
            ContentValues values = new ContentValues();
            values.put(MaBaseSQLite.COL_TYPE, Lecture.getType());
            values.put(MaBaseSQLite.COL_ADRESSE, Lecture.getAdresse());
            values.put(MaBaseSQLite.COL_ETAT, Lecture.getEtat());
            values.put(MaBaseSQLite.COL_DATE, Lecture.getEtat());
            values.put(MaBaseSQLite.COL_HEURE, Lecture.getEtat());
            return bdd.update(MaBaseSQLite.TABLE_LECTURES, values, MaBaseSQLite.COL_ID + " = " +id, null);
        }
     
        public int removeLectureeWithID(int id){
            //Suppression d'une commande de la BDD grâce à l'ID
            return bdd.delete(MaBaseSQLite.TABLE_LECTURES, MaBaseSQLite.COL_ID + " = " +id, null);
        }
     
        public int resetBDD(){
     
            return bdd.delete(MaBaseSQLite.TABLE_LECTURES, null, null);
        }
     
        public int nombreDeLigne(){
            //sélectionner toutes les lignes de la table lectures
            Cursor curseur = bdd.query(MaBaseSQLite.TABLE_LECTURES, null, null, null, null, null, null);
            //Renvoyer le nombre de lignes
            return curseur.getCount();
        }
     
        public ArrayList<Lecture> listeDesLectures(){
     
            ArrayList<Lecture> list_rapport = new  ArrayList<Lecture>();
     
            //Déclarer un objet Lecture qui servira de tampon
            Lecture c;
            //Exécution de la requête de sélection de toutes les lignes contenues dans la table
            Cursor curseur = bdd.query(MaBaseSQLite.TABLE_LECTURES, null, null, null, null, null, null);
            //Vérifier si le curseur contient au moins une ligne
            if (curseur != null) {
            //Se placer au premier enregistrement
                curseur.moveToFirst();
            //Parcourir les enregistrement tant que le dernier n'est pas encore lu (En quelque sorte)...
                while (!curseur.isAfterLast()) {
                    //Créer une commande
                    c = new Lecture();
                    //Affecter chaque valeur provenant d'un champ de la base de données à l'objet c
                    c.setId(curseur.getInt(curseur.getColumnIndex(MaBaseSQLite.COL_ID)));
                    c.setType(curseur.getString(curseur.getColumnIndex(MaBaseSQLite.COL_TYPE)));
                    c.setAdresse(curseur.getString(curseur.getColumnIndex(MaBaseSQLite.COL_ADRESSE)));
                    c.setEtat(curseur.getString(curseur.getColumnIndex(MaBaseSQLite.COL_ETAT)));
                    c.setDate(curseur.getString(curseur.getColumnIndex(MaBaseSQLite.COL_DATE)));
                    c.setHeure(curseur.getString(curseur.getColumnIndex(MaBaseSQLite.COL_HEURE)));
     
                    //Ajouter la lecture dans la liste
                    list_rapport.add(c);
                    //Passer à l'enregistrement suivant
                    curseur.moveToNext();
                }
                //Fermer le curseur
                curseur.close();
            }
            //Retourner la liste
            return list_rapport;
        }
     
    }
    MaBaseSQLite.java :
    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
    package com.example.wamove; /**
     * Created by Oier on 10/01/2015.
     */
     
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteDatabase.CursorFactory;
    import android.database.sqlite.SQLiteOpenHelper;
     
    public class MaBaseSQLite extends SQLiteOpenHelper {
     
        protected static final String TABLE_LECTURES = "table_lectures";
        protected static final String COL_ID = "ID";
        protected static final String COL_TYPE = "Type";
        protected static final String COL_ADRESSE = "Adresse";
        protected static final String COL_ETAT = "Etat";
        protected static final String COL_DATE = "Date";
        protected static final String COL_HEURE = "Heure";
     
        private static final String CREATE_BDD = "CREATE TABLE " + TABLE_LECTURES + " ("
                + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_TYPE + " STRING, "
                + COL_ADRESSE + " STRING, " + COL_ETAT + " STRING, " +
                COL_DATE + " STRING, " + COL_HEURE + " STRING);";
     
        public MaBaseSQLite(Context context, String name, CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
     
        @Override
        public void onCreate(SQLiteDatabase db) {
            //on créé la table à partir de la requête écrite dans la variable CREATE_BDD
            db.execSQL(CREATE_BDD);
        }
     
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //On peut fait ce qu'on veut ici moi j'ai décidé de supprimer la table et de la recréer
            //comme ça lorsque je change la version les id repartent de 0
            db.execSQL("DROP TABLE " + TABLE_LECTURES + ";");
            onCreate(db);
        }
     
    }
    Je viens enregistrer des données dans la bdd depuis cette activité :
    Supervision.xml :
    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
    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
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/fond"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.wamove.Supervision"
        android:gravity="center_horizontal">
     
        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:baselineAligned="false"
            android:orientation="vertical"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:gravity="center_vertical|center_horizontal"
            android:layout_centerInParent="true">
     
            <TextView
                android:id="@+id/editText_adr_ip"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:background="@null"
                android:ems="10"
                android:text="@string/lecture_de_bits"
                android:textStyle="italic" />
     
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/layout_border"
                android:orientation="vertical"
                android:gravity="center"
                android:id="@+id/linearLayout1"
                android:padding="10dp">
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="40dp"
                    android:layout_marginBottom="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_gravity="center"
                    android:id="@+id/linearLayout2"
                    android:padding="0dp"
                    android:gravity="center_vertical">
     
                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:text="@string/adresse_bit"
                        android:id="@+id/textView13"
                        android:layout_weight="2"
                        android:gravity="center|right"
                        android:layout_marginRight="5dp" />
     
                    <EditText
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:inputType="numberDecimal"
                        android:ems="10"
                        android:id="@+id/bit_adresse"
                        android:layout_weight="3"
                        android:padding="0dp"
                        android:gravity="center" />
     
                    <Button
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:text="@string/lire"
                        android:id="@+id/button5"
                        android:onClick="open_lire_bit"
                        android:gravity="center"
                        android:layout_weight="1" />
                </LinearLayout>
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="40dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_gravity="center"
                    android:padding="0dp"
                    android:gravity="center_vertical"
                    android:weightSum="5">
     
                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:text="@string/etat_bit"
                        android:id="@+id/textView14"
                        android:layout_weight="2"
                        android:gravity="center|right"
                        android:layout_marginRight="5dp" />
     
                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="fill_parent"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:id="@+id/bit_etat"
                        android:layout_weight="3"
                        android:gravity="center"
                        android:padding="0dp"
                        android:background="@drawable/layout_border" />
                </LinearLayout>
            </LinearLayout>
     
            <TextView
                android:id="@+id/editText_port"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
            	android:layout_marginLeft="10dp"
                android:ems="10"
            	android:background="@null"
                android:text="@string/lecture_de_mots"
            	android:textStyle="italic" />
     
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/layout_border"
                android:orientation="vertical"
                android:padding="10dp"
                android:gravity="center">
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="40dp"
                    android:layout_marginBottom="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_gravity="center"
                    android:id="@+id/linearLayout3"
                    android:padding="0dp"
                    android:gravity="center_vertical">
     
                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:text="@string/adresse_mot"
                        android:id="@+id/textView16"
                        android:layout_weight="2"
                        android:gravity="center|right"
                        android:layout_marginRight="5dp" />
     
                    <EditText
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:inputType="numberDecimal"
                        android:ems="10"
                        android:id="@+id/mot_adresse"
                        android:layout_weight="3"
                        android:padding="0dp"
                        android:gravity="center" />
     
                    <Button
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:onClick="open_lire_mot"
                        android:text="@string/lire"
                        android:id="@+id/button6"
                        android:gravity="center"
                        android:layout_weight="1" />
                </LinearLayout>
     
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="40dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_gravity="center"
                    android:padding="0dp"
                    android:gravity="center_vertical"
                    android:weightSum="5">
     
                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:text="@string/etat_mot"
                        android:id="@+id/textView16"
                        android:layout_weight="2"
                        android:gravity="center|right"
                        android:layout_marginRight="5dp" />
     
                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="fill_parent"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:id="@+id/mot_etat"
                        android:layout_weight="3"
                        android:background="@drawable/layout_border"
                        android:gravity="center" />
                </LinearLayout>
            </LinearLayout>
     
        </LinearLayout>
     
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="@string/supervision_2"
            android:id="@+id/textView24"
            android:gravity="center"
            android:textStyle="bold|italic"
            android:layout_alignParentTop="false"
            android:layout_alignParentLeft="false"
            android:layout_alignParentStart="true" />
     
        <Button
            android:id="@+id/button"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:background="@drawable/button_state"
            android:text="@string/afficher_historique"
            android:onClick="open_historique"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
     
    </RelativeLayout>
    Supervision.java :
    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
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    package com.example.wamove;
     
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.KeyEvent;
    import android.view.View;
    import android.widget.Toast;
    import java.util.Calendar;
    import android.widget.EditText;
    import android.widget.TextView;
     
    public class Supervision extends Activity {
     
        public static final String TEXT_1 = "TEXT_1";
        public static final String TEXT_2 = "TEXT_2";
     
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_supervision);
    	}
     
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
     
            TextView mTextView1 = (TextView) findViewById(R.id.bit_etat);
            TextView mTextView2 = (TextView) findViewById(R.id.mot_etat);
     
            outState.putString(TEXT_1, mTextView1.getText().toString());
            outState.putString(TEXT_2, mTextView2.getText().toString());
        }
     
        @Override
        protected void onRestoreInstanceState(Bundle savedState) {
            super.onRestoreInstanceState(savedState);
     
            TextView mTextView1 = (TextView) findViewById(R.id.bit_etat);
            TextView mTextView2 = (TextView) findViewById(R.id.mot_etat);
     
            mTextView1.setText(savedState.getString(TEXT_1));
            mTextView2.setText(savedState.getString(TEXT_2));
        }
     
    	public boolean onKeyDown(int keyCode, KeyEvent event)  
        {  
             //replaces the default 'Back' button action  
             if(keyCode==KeyEvent.KEYCODE_BACK)  
             {
            	Intent open_accueil=new Intent(Supervision.this,Accueil.class);
         		startActivity(open_accueil);
         		Supervision.this.finish();
             }  
             return true;  
       }
     
        public void open_historique(View v) {
     
            Intent open_historique=new Intent(Supervision.this,Historique.class);
            startActivity(open_historique);
            Supervision.this.finish();
     
        }
     
        public void open_lire_bit(View v){
     
            LecturesBDD lecturesBdd = new LecturesBDD(this);
     
            EditText bit_adresse = (EditText) findViewById(R.id.bit_adresse);
            TextView text_bit_etat=(TextView)findViewById(R.id.bit_etat);
     
            String bit_etat = "Etat";
            text_bit_etat.setText(bit_etat);
     
            //Création d'une commande
            Lecture lecture = new Lecture( "Bit", bit_adresse.getText().toString(), bit_etat,String.valueOf(Calendar.getInstance().get(Calendar.DATE)+"/"+Calendar.getInstance().get(Calendar.MONTH)+"/"+Calendar.getInstance().get(Calendar.YEAR)),String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE)));
     
            //On ouvre la base de données pour écrire dedans
            lecturesBdd.open();
     
            //On insère la commande que l'on vient de créer
            lecturesBdd.insertLecture(lecture);
     
            lecturesBdd.close();
     
        }
     
        public void open_lire_mot(View v){
     
            LecturesBDD lecturesBdd = new LecturesBDD(this);
     
            EditText mot_adresse = (EditText) findViewById(R.id.mot_adresse);
            TextView text_mot_etat=(TextView)findViewById(R.id.mot_etat);
     
            String mot_etat = "Etat";
            text_mot_etat.setText(mot_etat);
     
            //Création d'une commande
            Lecture lecture = new Lecture( "Mot", mot_adresse.getText().toString(), mot_etat,String.valueOf(Calendar.getInstance().get(Calendar.DATE)+"/"+Calendar.getInstance().get(Calendar.MONTH)+"/"+Calendar.getInstance().get(Calendar.YEAR)),String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE)));
     
            //On ouvre la base de données pour écrire dedans
            lecturesBdd.open();
     
            //On insère la commande que l'on vient de créer
            lecturesBdd.insertLecture(lecture);
     
            lecturesBdd.close();
     
        }
     
    }
    Maintenant pour ce qui est de l'ArrayAdapter personnalisé, j'ai fait comme ceci :
    - création de text_view.xml :
    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
    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
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
     
        android:padding="6dip">
        <!-- Id name -->
        <TextView
            android:id="@+id/Idname"
     
            android:layout_width="wrap_content"
            android:layout_height="26dip"
     
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
     
            android:textStyle="bold"
            android:singleLine="true"
            android:ellipsize="marquee"
            />
     
        <!-- Id data -->
        <TextView
            android:id="@+id/Iddata"
     
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
     
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@id/Idname"
     
            android:singleLine="true"
            android:ellipsize="marquee"
            />
     
        <!-- Type name -->
        <TextView
            android:id="@+id/Typename"
     
            android:layout_width="wrap_content"
            android:layout_height="26dip"
     
            android:layout_alignParentLeft="true"
            android:layout_below="@id/Idname"
     
            android:textStyle="bold"
            android:gravity="center_vertical"
            />
     
        <!-- Type data -->
        <TextView
            android:id="@+id/Typedata"
     
            android:layout_width="fill_parent"
            android:layout_height="26dip"
     
            android:layout_alignParentRight="true"
            android:layout_below="@id/Idname"
            android:layout_toRightOf="@id/Typename"
     
            android:gravity="center_vertical"
            />
     
        <!-- Adresse name -->
        <TextView
            android:id="@+id/Adressename"
     
            android:layout_width="wrap_content"
            android:layout_height="26dip"
     
            android:layout_alignParentLeft="true"
     
            android:textStyle="bold"
            android:gravity="center_vertical"
            android:layout_below="@+id/Typename" />
     
        <!-- Adresse data -->
        <TextView
            android:id="@+id/Adressedata"
     
            android:layout_width="fill_parent"
            android:layout_height="26dip"
     
            android:layout_alignParentRight="true"
            android:layout_below="@id/Typename"
            android:layout_toRightOf="@id/Adressedata"
     
            android:gravity="center_vertical"
            />
     
        <!-- Etat name -->
        <TextView
            android:id="@+id/Etatname"
     
            android:layout_width="wrap_content"
            android:layout_height="26dip"
     
            android:layout_alignParentLeft="true"
     
            android:textStyle="bold"
            android:gravity="center_vertical"
            android:layout_below="@+id/Adressename" />
     
        <!-- Etat data -->
        <TextView
            android:id="@+id/Etatdata"
     
            android:layout_width="fill_parent"
            android:layout_height="26dip"
     
            android:layout_alignParentRight="true"
            android:layout_below="@id/Adressename"
            android:layout_toRightOf="@id/Etatname"
     
            android:gravity="center_vertical"
            />
     
        <!-- Date name -->
        <TextView
            android:id="@+id/Datename"
     
            android:layout_width="wrap_content"
            android:layout_height="26dip"
     
            android:layout_alignParentLeft="true"
     
            android:textStyle="bold"
            android:gravity="center_vertical"
            android:layout_below="@+id/Etatname" />
     
        <!-- Date data -->
        <TextView
            android:id="@+id/Datedata"
     
            android:layout_width="fill_parent"
            android:layout_height="26dip"
     
            android:layout_alignParentRight="true"
            android:layout_below="@id/Etatname"
            android:layout_toRightOf="@id/Datename"
     
            android:gravity="center_vertical"
            />
     
        <!-- Heure name -->
        <TextView
            android:id="@+id/Heurename"
     
            android:layout_width="wrap_content"
            android:layout_height="26dip"
     
            android:layout_alignParentLeft="true"
     
            android:textStyle="bold"
            android:gravity="center_vertical"
            android:layout_below="@+id/Datename" />
     
        <!-- Heure data -->
        <TextView
            android:id="@+id/Heuredata"
     
            android:layout_width="fill_parent"
            android:layout_height="26dip"
     
            android:layout_alignParentRight="true"
            android:layout_below="@id/Datename"
            android:layout_toRightOf="@id/Heurename"
     
            android:gravity="center_vertical"
            />
     
    </RelativeLayout>
    Puis de ItemAdapter.java :
    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
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    package com.example.wamove;
     
    import java.util.ArrayList;
     
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.TextView;
     
    public class ItemAdapter extends ArrayAdapter<Lecture> {
     
        // declaring our ArrayList of items
        private ArrayList<Lecture> objects;
     
        /* here we must override the constructor for ArrayAdapter
        * the only variable we care about now is ArrayList<Lecture> objects,
        * because it is the list of objects we want to display.
        */
        public ItemAdapter(Context context, int textViewResourceId, ArrayList<Lecture> objects) {
            super(context, textViewResourceId, objects);
            this.objects = objects;
        }
     
        /*
         * we are overriding the getView method here - this is what defines how each
         * list item will look.
         */
        public View getView(int position, View convertView, ViewGroup parent){
     
            // assign the view we are converting to a local variable
            View v = convertView;
     
            // first check to see if the view is null. if so, we have to inflate it.
            // to inflate it basically means to render, or show, the view.
            if (v == null) {
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = inflater.inflate(R.layout.text_view, null);
            }
     
    		/*
    		 * Recall that the variable position is sent in as an argument to this method.
    		 * The variable simply refers to the position of the current object in the list. (The ArrayAdapter
    		 * iterates through the list we sent it)
    		 * 
    		 * Therefore, i refers to the current Item object.
    		 */
            Lecture i = objects.get(position);
     
            if (i != null) {
     
                // This is how you obtain a reference to the TextViews.
                // These TextViews are created in the XML files we defined.
     
                TextView Idname = (TextView) v.findViewById(R.id.Idname);
                TextView Iddata = (TextView) v.findViewById(R.id.Iddata);
                TextView Typename = (TextView) v.findViewById(R.id.Typename);
                TextView Typedata = (TextView) v.findViewById(R.id.Typedata);
                TextView Adressename = (TextView) v.findViewById(R.id.Adressename);
                TextView Adressedata = (TextView) v.findViewById(R.id.Adressedata);
                TextView Etatname = (TextView) v.findViewById(R.id.Etatname);
                TextView Etatdata = (TextView) v.findViewById(R.id.Etatdata);
                TextView Datename = (TextView) v.findViewById(R.id.Datename);
                TextView Datedata = (TextView) v.findViewById(R.id.Datedata);
                TextView Heurename = (TextView) v.findViewById(R.id.Heurename);
                TextView Heuredata = (TextView) v.findViewById(R.id.Heuredata);
     
                // check to see if each individual textview is null.
                // if not, assign some text!
                if (Idname != null){
                    Idname.setText("Id : ");
                }
                if (Iddata != null){
                    Iddata.setText(i.getId());
                }
                if (Typename != null){
                    Typename.setText("Type : ");
                }
                if (Typedata != null){
                    Typedata.setText(i.getType());
                }
                if (Adressename != null){
                    Adressename.setText("Adresse : ");
                }
                if (Adressedata != null){
                    Adressedata.setText(i.getAdresse());
                }
                if (Etatname != null){
                    Etatname.setText("Etat : ");
                }
                if (Etatdata != null){
                    Etatdata.setText(i.getEtat());
                }
                if (Datename != null){
                    Datename.setText("Date : ");
                }
                if (Datedata != null){
                    Datedata.setText(i.getDate());
                }
                if (Heurename != null){
                    Heurename.setText("Heure : ");
                }
                if (Heuredata != null){
                    Heuredata.setText(i.getHeure());
                }
            }
     
            // the view must be returned to our activity
            return v;
     
        }
     
    }
    Je veux donc afficher les données de ma bdd dans le layout Historique.xml: :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.example.wamove.Historique">
     
        <ListView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/listView" />
    </RelativeLayout>
    Via son Historique.java :
    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
    package com.example.wamove;
     
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.KeyEvent;
    import java.util.*;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.ListAdapter;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import java.util.ArrayList;
     
     
    public class Historique extends Activity {
     
        private ListView list;
        private ListAdapter listAdaptor;
        private SQLiteDatabase database;
        private ItemAdapter m_adapter;
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_historique);
     
            list = (ListView) findViewById(R.id.listView);
     
            LecturesBDD lecturesBdd = new LecturesBDD(this);
     
            lecturesBdd.open();
     
            ArrayList<Lecture> liste = lecturesBdd.listeDesLectures();
     
            m_adapter = new ItemAdapter(this, R.layout.text_view, liste);
            list.setAdapter(m_adapter);
     
            lecturesBdd.close();
        }
     
        public boolean onKeyDown(int keyCode, KeyEvent event)
        {
            //replaces the default 'Back' button action
            if(keyCode==KeyEvent.KEYCODE_BACK)
            {
                Intent open_supervision=new Intent(Historique.this,Supervision.class);
                startActivity(open_supervision);
                Historique.this.finish();
            }
            return true;
        }
    }
    Le crash vient donc lorsque j'exécute le code
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    m_adapter = new ItemAdapter(this, R.layout.text_view, liste);
    J'ai tiré ce code depuis ce tuto.

    Je n'arrive pas du tout à voir d'où vient l'erreur...

    Encore merci pour ton aide et pour le temps que tu m'accordes !

  17. #17
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Tu dois au moins trouver le message d'erreur qu'est affiché. Sinon, on ne saura deviner car il n'est pas trop facile (pour moi personnellement) de parcourir tout ton code

  18. #18
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    149
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 149
    Points : 59
    Points
    59
    Par défaut
    J'ai finalement réussi à trouver l'erreur dans mon code, et tout fonctionne parfaitement maintenant ! Je te remercie énormément pour tout l'aide que tu m'as apporté, j'ai appris beaucoup de choses grâce à toi !

  19. #19
    Nouveau Candidat au Club
    Homme Profil pro
    ingénieur R&D
    Inscrit en
    Janvier 2015
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Hautes Alpes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : ingénieur R&D
    Secteur : Industrie

    Informations forums :
    Inscription : Janvier 2015
    Messages : 1
    Points : 1
    Points
    1
    Par défaut problème avec un programme similaire
    Bonjour à vous, je suis débutant en programmation pour android, et il se trouve que j'ai un programme similaire au tient vu que je suis partie de la même base que toi (exemple table_livre : a-renouard.developpez.com)
    lorsque je récupère le code situé sur cette page, il fonctionne, mais lorsque je veux faire un nouveau programme en changeant juste le nom des classe, objet etc, il ne fonctionne plus.
    j'ai l'impression que j'ai un problème avec la query: dans mon scoreBDD (équivalent du livreBDD ou de ton LectureBDD) vu que celui ci ne me retourne pas mon score:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    public Score getScoreWithLevel(String level) {
            Cursor c = bdd.query(MaBaseSQLite.TABLE_SCORE, new String[]{MaBaseSQLite.COL_ID, MaBaseSQLite.COL_LEVEL, MaBaseSQLite.COL_BESTTIME}, MaBaseSQLite.COL_LEVEL + " LIKE \"" + level + "\"", null, null, null, null);
     
            return cursorToScore(c);
        }
    ou le cursorToScore est :
    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
      private Score cursorToScore(Cursor c){
     
            if (c.getCount() == 0)
                return null;
     
            c.moveToFirst();
            Score score = new Score();
            score.setId(c.getInt(NUM_COL_ID));
            score.setLevel(c.getString(NUM_COL_LEVEL));
            score.setBesttime(c.getString(NUM_COL_BESTTIME));
     
            c.close();
     
            return score;
        }
    sachant que le programme de base tourne très bien avec
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    public Livre getLivreWithTitre(String titre) {
            //Récupère dans un Cursor les valeurs correspondant à un livre contenu dans la BDD (ici on sélectionne le livre grâce à son titre)
            Cursor c = bdd.query(MaBaseSQLite.TABLE_LIVRES, new String[]{MaBaseSQLite.COL_ID, MaBaseSQLite.COL_ISBN, MaBaseSQLite.COL_TITRE}, MaBaseSQLite.COL_TITRE + " LIKE \"" + titre + "\"", null, null, null, null);
            return cursorToLivre(c);
        }
    j'ai juste changer les noms...cela fait trois jour que je m'acharne à essayer de comprendre d'ou viens mon problème...
    pouvez-vous m'aider? merci

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

Discussions similaires

  1. Réponses: 3
    Dernier message: 02/02/2014, 22h17
  2. [Débutant] connexion Visual studio base de données odbc
    Par IAGISG dans le forum VB.NET
    Réponses: 1
    Dernier message: 29/08/2011, 16h47

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