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

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

Android Discussion :

ListeView From SQLite


Sujet :

Android

  1. #1
    Nouveau membre du Club
    Homme Profil pro
    Administrateur systèmes et réseaux
    Inscrit en
    Mai 2014
    Messages
    43
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : Maroc

    Informations professionnelles :
    Activité : Administrateur systèmes et réseaux

    Informations forums :
    Inscription : Mai 2014
    Messages : 43
    Points : 31
    Points
    31
    Par défaut ListeView From SQLite
    Salut les informaticiens, je veux crée une listview a partir de ma base de donnée Sqlite, mais j'ai rencontré une problème au niveau de la requête SELECT * :

    voila mon code:

    mon classeDAO

    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
    package formationrs.rrapp;
     
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
     
    import java.util.ArrayList;
    import java.util.LinkedList;
     
    import PrincipaleClasses.MesProjets;
    import PrincipaleClasses.Note;
     
    /**
     * Created by amtech on 29/07/2015.
     */
    public class ProjetDB {
        private static final int VERSION_BDD = 3;
        private static final String NOM_BDD = "projet.db";
     
        private static final String TABLE_PROJET = "table_projet";
        private static final String COL_IDPROJET = "IDP";
        private static final int NUM_COL_ID =0;
        private static final String COL_DATED_PROJET = "dated";
        private static final int NUM_COL_DATED =1;
        private static final String COL_DATEF_PROJET = "datef";
        private static final int NUM_COL_DATEF =2;
        private static final String COL_NOM_PROJET = "nom_projet";
        private static final int NUM_COL_NOMP=3;
     
     
     
        private SQLiteDatabase Pr_bd;
     
        private DataBaseClasse maBaseProjet;
        public int  userId;
     
        public ProjetDB(Context context){
            //On crée la BDD et sa table
            maBaseProjet = new DataBaseClasse(context, NOM_BDD, null, VERSION_BDD);
        }
     
        public void open(){
            //on ouvre la BDD en écriture
            Pr_bd = maBaseProjet.getWritableDatabase();
        }
     
        public void close(){
            //on ferme l'accès à la BDD
            Pr_bd.close();
        }
     
        public SQLiteDatabase getBDD(){
            return   Pr_bd;
        }
     
        public long insertprojet( MesProjets projet){
     
            //Création d'un ContentValues (fonctionne comme une HashMap)
            ContentValues values = new ContentValues();
            //on lui ajoute une valeur associée à une clé (qui est le nom de la colonne dans laquelle on veut mettre la valeur)
            values.put(COL_NOM_PROJET, MesProjets.getNomP());
            values.put(COL_DATED_PROJET, MesProjets.getDateD());
            values.put(COL_DATEF_PROJET, MesProjets.getDateF());
            //on insère l'objet dans la BDD via le ContentValues
            return Pr_bd.insert(TABLE_PROJET, null, values);
        }
        public int updateprojet(String nom, MesProjets projet){
            //La mise à jour d'une note dans la BDD fonctionne plus ou moins comme une insertion
            //il faut simplement préciser quel note on doit mettre à jour grâce à l'ID
            ContentValues values = new ContentValues();
            values.put(COL_NOM_PROJET, MesProjets.getNomP());
            values.put(COL_DATED_PROJET, MesProjets.getDateD());
            values.put(COL_DATEF_PROJET, MesProjets.getDateF());
          // return Pr_bd.update(TABLE_PROJET, values, COL_NOM_PROJET + " = " +nom, null);
     
     
        return  Pr_bd.update(ProjetDB.TABLE_PROJET, values,ProjetDB.COL_NOM_PROJET + " =? ", new String[] {nom});
        }
     
        public int removeprojetWithName(String nom){
            //Suppression d'un livre de la BDD grâce à l'ID
            return Pr_bd.delete(TABLE_PROJET, COL_NOM_PROJET + " = " +nom, null);
        }
     
        public MesProjets getprojetWithNom(String nom){
            //Récupère dans un Cursor les valeurs correspondant à un projet contenu dans la BDD (ici on sélectionne la note grâce à son titre)
            Cursor c = Pr_bd.query(TABLE_PROJET, new String[] {COL_IDPROJET, COL_DATED_PROJET, COL_DATEF_PROJET, COL_NOM_PROJET, }, COL_NOM_PROJET + " LIKE \"" + nom +"\"", null, null, null, null);
            return cursorToLivre(c);
        }
        public MesProjets getprojetWithDateD(int dated){
            //Récupère dans un Cursor les valeurs correspondant à un projet contenu dans la BDD (ici on sélectionne la note grâce à son titre)
            Cursor c = Pr_bd.query(TABLE_PROJET, new String[] {COL_IDPROJET, COL_DATED_PROJET, COL_DATEF_PROJET, COL_NOM_PROJET, }, COL_DATED_PROJET + " LIKE \"" + dated +"\"", null, null, null, null);
            return cursorToLivre(c);
        }
        public MesProjets getprojetWithDateF(int datef){
            //Récupère dans un Cursor les valeurs correspondant à un projet contenu dans la BDD (ici on sélectionne la note grâce à son titre)
            Cursor c = Pr_bd.query(TABLE_PROJET, new String[] {COL_IDPROJET, COL_DATED_PROJET, COL_DATEF_PROJET, COL_NOM_PROJET, }, COL_DATEF_PROJET + " LIKE \"" + datef +"\"", null, null, null, null);
            return cursorToLivre(c);
        }
        public ArrayList<MesProjets> selectionnerAll () //template de produits, pour tous les afficher
        {
            MesProjets p; //nouvel objet
            //
            ArrayList<MesProjets> mesProjets = new ArrayList<MesProjets>(); //nouvelle instance
            Cursor c = Pr_bd.rawQuery("SELECT * FROM TABLE_PROJET",null ); //requete SQLite
     
     
     
           for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) //boucle for avec des fonction pré-faites qui va du premier élément au dernier
            {
                p = new MesProjets (0,0, null); //on définit un objet avec des valeurs nulles
                p.setNomP(c.getString(NUM_COL_NOMP));//et pour chaque attribut on récup les valeurs
                p.setDateD(c.getInt(NUM_COL_DATED));
                p.setDateF(c.getInt(NUM_COL_DATEF));
     
                mesProjets.add(p); // on rajoute le produit a la liste
            }
     
            return mesProjets; //et on affiche tout
        }
            //Cette méthode permet de convertir un cursor en un projet
        private MesProjets 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éé un livre
            MesProjets mprojet = new MesProjets();
            //on lui affecte toutes les infos grâce aux infos contenues dans le Cursor
     
            MesProjets.setNomP(c.getString(NUM_COL_NOMP));
            MesProjets.setDateD(c.getInt(NUM_COL_DATED));
            MesProjets.setDateF(c.getInt(NUM_COL_DATEF));
     
            //On ferme le cursor
            c.close();
     
            //On retourne le livre
            return mprojet;
        }
    }
    MainActivity :

    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
    package formationrs.rrapp;
     
            import java.util.ArrayList;
            import android.app.Activity;
            import android.app.AlertDialog;
            import android.content.Context;
            import android.content.DialogInterface;
            import android.content.Intent;
            import android.database.Cursor;
            import android.database.sqlite.SQLiteDatabase;
            import android.os.Bundle;
            import android.view.LayoutInflater;
            import android.view.View;
            import android.view.View.OnClickListener;
            import android.view.ViewGroup;
            import android.widget.AdapterView;
            import android.widget.AdapterView.OnItemClickListener;
            import android.widget.AdapterView.OnItemLongClickListener;
            import android.widget.BaseAdapter;
            import android.widget.ListView;
            import android.widget.TextView;
            import android.widget.Toast;
     
            import PrincipaleClasses.MesProjets;
     
    public class Projet_Activity extends Activity {
     
        ProjetDB monprojetDB = new ProjetDB(this);
     
        private ArrayList<String> userId = new ArrayList<String>();
        private ArrayList<String> projet_Name = new ArrayList<String>();
        private ArrayList<String> projet_dated = new ArrayList<String>();
        private ArrayList<String> projet_datef = new ArrayList<String>();
     
        private ListView projetList;
        private AlertDialog.Builder build;
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.list_projet);
     
            projetList = (ListView) findViewById(R.id.List);
     
     
     
            //add new record
            findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
     
                public void onClick(View v) {
     
                    Intent i = new Intent(getApplicationContext(), ADD_Projet.class);
                    i.putExtra("update", false);
                    startActivity(i);
     
                }
            });
     
            //click to update data
            projetList.setOnItemClickListener(new OnItemClickListener() {
     
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
     
                    Intent i = new Intent(getApplicationContext(), ADD_Projet.class);
                    i.putExtra("Name", projet_Name.get(arg2));
                    i.putExtra("Dated", projet_dated.get(arg2));
                    i.putExtra("Datef", projet_dated.get(arg2));
                    i.putExtra("ID", userId.get(arg2));
                    i.putExtra("update", true);
                    startActivity(i);
     
                }
            });
     
            //long click to delete data
            projetList.setOnItemLongClickListener(new OnItemLongClickListener() {
     
                public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
     
                    build = new AlertDialog.Builder(Projet_Activity.this);
                    build.setTitle("Delete " + projet_Name.get(arg2) + " " + projet_dated.get(arg2) + " " + projet_datef.get(arg2));
                    build.setMessage("Do you want to delete ?");
                    build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
     
                        public void onClick(DialogInterface dialog, int which) {
     
                            Toast.makeText( getApplicationContext(),
                                    projet_Name.get(arg2) + " "
                                            + projet_dated.get(arg2)+ " " + projet_datef.get(arg2)
                                            + " is deleted.", Toast.LENGTH_LONG).show();
     
                            monprojetDB.removeprojetWithName(userId.get(arg2));
                            displayData();
                            dialog.cancel();
                        }
                    });
     
                    build.setNegativeButton("No", new DialogInterface.OnClickListener() {
     
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    AlertDialog alert = build.create();
                    alert.show();
     
                    return true;
                }
            });
        }
     
        @Override
        protected void onResume() {
            displayData();
            super.onResume();
        }
     
        /**
         * displays data from SQLite
         */
        private void displayData() {
     
            Cursor mCursor = (Cursor) monprojetDB. selectionnerAll ()
     
     
          userId.clear();
            projet_Name.clear();
            projet_dated.clear();
            projet_datef.clear();
     
            DisplayAdapter disadpt = new DisplayAdapter(Projet_Activity.this,userId, projet_Name, projet_dated,projet_datef);
            projetList.setAdapter(disadpt);
            mCursor.close();
        }
        public class DisplayAdapter extends BaseAdapter {
            private Context mContext;
            private ArrayList<String> id;
            private ArrayList<String> Name;
            private ArrayList<String> Dated;
            private ArrayList<String> Datef;
     
     
            public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> name, ArrayList<String> dated, ArrayList<String> datef ) {
                this.mContext = c;
     
                this.id = id;
                this.Name = name;
                this.Dated= dated;
                this.Datef= datef;
            }
     
            public int getCount() {
                // TODO Auto-generated method stub
                return id.size();
            }
     
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return null;
            }
     
            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return 0;
            }
     
            public View getView(int pos, View child, ViewGroup parent) {
                Holder mHolder;
                LayoutInflater layoutInflater;
                if (child == null) {
                    layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    child = layoutInflater.inflate(R.layout.listadp, null);
                    mHolder = new Holder();
                    mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
                    mHolder.txt_Name = (TextView) child.findViewById(R.id.txt_Name);
                    mHolder.txt_Dated = (TextView) child.findViewById(R.id.txt_Dated);
                    mHolder.txt_Datef = (TextView) child.findViewById(R.id.txt_Datef);
                    child.setTag(mHolder);
                } else {
                    mHolder = (Holder) child.getTag();
                }
                mHolder.txt_id.setText(id.get(pos));
                mHolder.txt_Name.setText(Name.get(pos));
                mHolder.txt_Dated.setText(Dated.get(pos));
                mHolder.txt_Datef.setText(Datef.get(pos));
     
                return child;
            }
     
            public class Holder {
                TextView txt_id;
                TextView txt_Name;
                TextView txt_Dated;
                TextView txt_Datef;
            }
     
        }
        }
    base de donnée:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     private static final String TABLE_PROJET = "table_projet";
        private static final String COL_IDPROJET = "IDP";
        private static final String COL_NOM_PROJET = "nom_projet";
        private static final String COL_DATED_PROJET = "dated";
        private static final String COL_DATEF_PROJET = "datef";
     
     
     
     
        private static final String CREATE_PROJET = "CREATE TABLE " + TABLE_PROJET + "("
                + COL_IDPROJET + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_NOM_PROJET + " TEXT NOT NULL, "
                + COL_DATED_PROJET + " DATE, " + COL_DATEF_PROJET + " DATE );";

    message d'erreur:

    java.lang.NullPointerException
    at formationrs.rrapp.ProjetDB.selectionnerAll(ProjetDB.java:106)
    at formationrs.rrapp.Projet_Activity.displayData(Projet_Activity.java:123)
    at formationrs.rrapp.Projet_Activity.onResume(Projet_Activity.java:114)

    merci de m'assister

  2. #2
    Expert éminent

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

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

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Sans lire le code:
    java.lang.NullPointerException
    at formationrs.rrapp.ProjetDB.selectionnerAll(ProjetDB.java:106)
    =>
    Utilisation d'une référence nulle ligne 106 de ProjetDB.java (fonction "selectionnerAll" de la classe formationsr.rrapp.ProjetDB).

    En lisant le code à cette ligne:
    Cursor c = Pr_bd.rawQuery("SELECT * FROM TABLE_PROJET",null ); //requete SQLite
    =>
    Pr_db est null (c'est la seule utilisation de référence).
    Au passage: l'utilisation de '_' est proscrit en java (enfin... fortement non recommandé) et une variable membre (comme Pr_db) commence *obligatoirement* par une minuscule. Pr pour pointeur ? On n'est pas en C, il n'existe pas de pointeur en Java, uniquement des références. "Pr" est donc inutile. sqliteDatabase par exemple serait plus adapté comme nom.


    En listant le code autour:
    Il semble que la fonction "open" qui permet de setuper correctement cette référence n'est jamais appelé.
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  3. #3
    Nouveau membre du Club
    Homme Profil pro
    Administrateur systèmes et réseaux
    Inscrit en
    Mai 2014
    Messages
    43
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : Maroc

    Informations professionnelles :
    Activité : Administrateur systèmes et réseaux

    Informations forums :
    Inscription : Mai 2014
    Messages : 43
    Points : 31
    Points
    31
    Par défaut
    Merci Bqq, nicorman

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

Discussions similaires

  1. qui connait sqlite ?
    Par Emmanuel Lecoester dans le forum SQLite
    Réponses: 23
    Dernier message: 19/02/2010, 13h44
  2. [COUNT] select ... from ... where count !
    Par tmcgrady dans le forum Langage SQL
    Réponses: 5
    Dernier message: 30/11/2007, 17h29
  3. SYBASE SELECT imbriqué clause FROM
    Par Nicolas Martel dans le forum Sybase
    Réponses: 2
    Dernier message: 19/11/2003, 15h28
  4. Automatiser la mise à jour de la bD SQL SERVER from Access
    Par Nadaa dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 11/11/2003, 15h23
  5. equivalent de select nextval from dual en SQL-Server ?
    Par toze dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 15/10/2003, 09h17

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