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

Composants graphiques Android Discussion :

Cliquer sur un item d'une listview pour lancer une nouvelle activité


Sujet :

Composants graphiques Android

  1. #1
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2015
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2015
    Messages : 67
    Points : 108
    Points
    108
    Par défaut Cliquer sur un item d'une listview pour lancer une nouvelle activité
    Bonsoir,

    Je suis actuellement bloqué avec une listview, j'obtiens bien les données escomptées grâce au code suivant mais je n'arrive pas à cliquer sur un item pour afficher le nom de l'hôtel par exemple. Pouvez-vous m'aider

    Nom : rec.JPG
Affichages : 2822
Taille : 32,8 Ko

    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
     
     
            @Override
            public void onClick(View v){
                switch (v.getId()) {
                    case R.id.retour:
                        Intent intent = new Intent(this, MainActivity.class);
                        startActivity(intent);
                        break;
     
                    case R.id.recherchons:
     
                        arrayList.clear();
                        String choixcategorie = Categorie.getSelectedItem().toString();
                        String choixville = Ville.getSelectedItem().toString();
                        String lechoix = "";
                        Choixnom = (EditText) findViewById(R.id.choixx);
                        lechoix = Choixnom.getText().toString();
     
                        if (lechoix != "" & choixcategorie != "Categorie" & choixville != "Ville") {
                            try {
                                Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and commune =" + "'" + choixville + "'" + " and type=" + "'" + choixcategorie + "'");
                                if (cursor != null) {
                                    if (cursor.moveToFirst()) {
                                        do {
                                            Item item = new Item();
                                            //item.setId(cursor.getString(0));
                                            item.setType(cursor.getString(1));
                                            item.setNom(cursor.getString(2));
                                            arrayList.add(item);
                                            /*ImageView img = (ImageView) findViewById(R.id.imagedelacategorie);
                                            img.setImageResource(R.drawable.ic_commerce);*/
     
                                        } while (cursor.moveToNext());
                                    }
                                }
                            } catch (SQLException e) {
                            }
     
                            adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
                            listView = (ListView) findViewById(R.id.list_item);
                            listView.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
     
    /* ne marche pas 
     
                            listView.setOnItemClickListener(new OnItemClickListener() {
                                @Override
                                @SuppressWarnings("unchecked")
                                public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                                    HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position);
                                    AlertDialog.Builder adb = new AlertDialog.Builder(ButtonRecherche.this);
                                    adb.setTitle("Sélection Item");
                                    adb.setMessage("Votre choix : ");//+map.get("titre")
                                    adb.setPositiveButton("Ok", null);
                                    adb.show();
                                }
                            });*/
    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
     
     
    public class Adapter extends ArrayAdapter<Item> {
        private Activity activity;
        int id;
        ArrayList<Item> items;
        public Adapter(Activity context, int resource, ArrayList<Item> objects) {
            super(context, resource, objects);
            this.activity=context;
            this.id=resource;
            this.items=objects;
        }
     
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView==null){
                LayoutInflater inflater=activity.getLayoutInflater();
                convertView=inflater.inflate(id,null);
            }
            Item item=items.get(position);
            TextView tv_type= (TextView) convertView.findViewById(R.id.tv_type);
            TextView tv_nom= (TextView) convertView.findViewById(R.id.tv_nom);
     
     
            tv_type.setText(item.getType());
            tv_nom.setText(item.getNom());
     
     
            return convertView;
        }
    }

  2. #2
    Expert éminent

    Avatar de Feanorin
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    4 589
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 4 589
    Points : 9 149
    Points
    9 149
    Par défaut
    Salut,

    il faut bien que tu utilises la fonction setOnItemClickListener que tu as commenté.

    Après il est conseillé maintenant d'utiliser les Recyclerview au lieu des ListView.
    Responsable Android de Developpez.com (Twitter et Facebook)
    Besoin d"un article/tutoriel/cours sur Android, consulter la page cours
    N'hésitez pas à consulter la FAQ Android et à poser vos questions sur les forums d'entraide mobile d'Android.

  3. #3
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2015
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2015
    Messages : 67
    Points : 108
    Points
    108
    Par défaut
    Merci de ta réponse mais quand j'utilise cette fonction rien ne se passe

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
                            listView.setOnItemClickListener(new OnItemClickListener() {
                                @Override
                                @SuppressWarnings("unchecked")
                                public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                                    HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position);
                                    AlertDialog.Builder adb = new AlertDialog.Builder(ButtonRecherche.this);
                                    adb.setTitle("Sélection Item");
                                    adb.setMessage("Votre choix : ");
                                    adb.setPositiveButton("Ok", null);
                                    adb.show();
                                }
                            });

  4. #4
    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,

    esaie ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
     
    //Ton code ici.....
                }
            });
    Christian Djo,
    Plus tu apprends sérieusement, plus tu te rapproches d'un savoir noble. Une chose est certaine, les difficultés ne s'écarteront de ton chemin...

    Tu es nouveau dans le développement Android, la page des COURS est là pour te faciliter la vie
    Tu peux trouver la réponse à ta question dans la FAQ
    Retrouvez mon tutoriel sur la consommation des services web SOAP
    Pense à voter positivement en appuyant sur en bas à droite de la réponse qui t'a donné une piste de solution.

  5. #5
    Membre confirmé

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Août 2014
    Messages
    262
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 30
    Localisation : Burkina Faso

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Finance

    Informations forums :
    Inscription : Août 2014
    Messages : 262
    Points : 634
    Points
    634
    Par défaut
    Citation Envoyé par kopbuc Voir le message
    Bonsoir,

    Je suis actuellement bloqué avec une listview, j'obtiens bien les données escomptées grâce au code suivant mais je n'arrive pas à cliquer sur un item pour afficher le nom de l'hôtel par exemple. Pouvez-vous m'aider

    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
     
     
            @Override
            public void onClick(View v){
                switch (v.getId()) {
                    case R.id.retour:
                        Intent intent = new Intent(this, MainActivity.class);
                        startActivity(intent);
                        break;
     
                    case R.id.recherchons:
     
                        arrayList.clear();
                        String choixcategorie = Categorie.getSelectedItem().toString();
                        String choixville = Ville.getSelectedItem().toString();
                        String lechoix = "";
                        Choixnom = (EditText) findViewById(R.id.choixx);
                        lechoix = Choixnom.getText().toString();
     
                        if (lechoix != "" & choixcategorie != "Categorie" & choixville != "Ville") {
                            try {
                                Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and commune =" + "'" + choixville + "'" + " and type=" + "'" + choixcategorie + "'");
                                if (cursor != null) {
                                    if (cursor.moveToFirst()) {
                                        do {
                                            Item item = new Item();
                                            //item.setId(cursor.getString(0));
                                            item.setType(cursor.getString(1));
                                            item.setNom(cursor.getString(2));
                                            arrayList.add(item);
                                            /*ImageView img = (ImageView) findViewById(R.id.imagedelacategorie);
                                            img.setImageResource(R.drawable.ic_commerce);*/
     
                                        } while (cursor.moveToNext());
                                    }
                                }
                            } catch (SQLException e) {
                            }
     
                            adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
                            listView = (ListView) findViewById(R.id.list_item);
                            listView.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
     
    /* ne marche pas 
     
                            listView.setOnItemClickListener(new OnItemClickListener() {
                                @Override
                                @SuppressWarnings("unchecked")
                                public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                                    HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position);
                                    AlertDialog.Builder adb = new AlertDialog.Builder(ButtonRecherche.this);
                                    adb.setTitle("Sélection Item");
                                    adb.setMessage("Votre choix : ");//+map.get("titre")
                                    adb.setPositiveButton("Ok", null);
                                    adb.show();
                                }
                            });*/
    Je pense que ce code-ci est incomplet, je ne vois pas la fin de la méthode public void onClick(View v), est-ce dans cette méthode que tu essaies d'appeler

    le setOnItemClickListener sur ta ListView ? Si c'est le cas, je doute fort. Si tu veux bien recoller le code exact çà aiderait beaucoup.
    Aujourd'hui apprenant, demain appreneur.
    N'accuse pas le puits d'être trop profond,
    c'est peut-être ta corde qui est trop courte

  6. #6
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2015
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2015
    Messages : 67
    Points : 108
    Points
    108
    Par défaut
    Bonsoir, merci de votre aide, j'essaye vos propositions et en attendant je poste le code entier j'utilisais bien la méthode dans le onclick.
    Recherche

    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
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
     
     
    package com.cyatophilum.projetmenu;
     
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ImageButton;
    import android.widget.ImageView;
    import android.widget.Spinner;
     
    import java.util.ArrayList;
    import java.util.List;
    import android.database.Cursor;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageButton;
    import android.widget.ListView;
    import android.view.View;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.TextView;
    import android.widget.Toast;
     
    import java.sql.SQLException;
    import java.util.ArrayList;
     
    public class ButtonRecherche extends AppCompatActivity implements View.OnClickListener {
        private ImageButton retour = null;
        private Spinner Categorie, Ville = null;
        ListView listView;
        private DatabaseHelper dbHelper;
        Adapter adapter;
        ArrayList<Item> arrayList = new ArrayList<Item>();
        ImageButton recherche = null;
        ImageButton rechercheavancee = null;
        EditText Choixnom;
     
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_recherche);
     
            dbHelper = new DatabaseHelper(this);
            try {
                dbHelper.checkAndCopyDatabase();
                dbHelper.openDatabase();
            } catch (SQLException e) {
     
            }
     
            recherche = (ImageButton) findViewById(R.id.recherchons);
            recherche.setOnClickListener(this);
     
            Categorie = (Spinner) findViewById(R.id.spinner1);
            Ville = (Spinner) findViewById(R.id.spinner2);
            List<String> exemple1 = new ArrayList<String>();
            List<String> exemple2 = new ArrayList<String>();
     
            exemple1.add("Categorie");
            exemple1.add("Commerce et service");
            exemple1.add("Dégustation");
            exemple1.add("Equipement");
            exemple1.add("Hébergement collectif");
            exemple1.add("Hébergement locatif");
            exemple1.add("Hôtellerie");
            exemple1.add("Hôtellerie plein air");
            exemple1.add("Patrimoine culturel");
            exemple1.add("Patrimoine naturel");
            exemple1.add("Restauration");
     
            exemple2.add("Ville");
            exemple2.add("Lyon 2ème");
            exemple2.add("Lyon 1er");
     
            ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, exemple1);
            ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, exemple2);
            //Le layout par defaut est android.R.layout.simple_spinner_dropdown_item
            adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            Ville.setAdapter(adapter2);
            Categorie.setAdapter(adapter1);
     
            retour = (ImageButton) findViewById(R.id.retour);
            retour.setOnClickListener(this);
     
        }
     
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.retour:
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                    break;
     
                /*case R.id.button2:
                    TextView textView = new TextView(this);
                    textView.setText("Pas encore d�fini");
                    break;
                    */
     
                case R.id.recherchons:
     
                    arrayList.clear();
                    String choixcategorie = Categorie.getSelectedItem().toString();
                    String choixville = Ville.getSelectedItem().toString();
                    String lechoix = "";
                    Choixnom = (EditText) findViewById(R.id.choixx);
                    lechoix = Choixnom.getText().toString();
     
                    if (lechoix != "" & choixcategorie != "Categorie" & choixville != "Ville") {
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and commune =" + "'" + choixville + "'" + " and type=" + "'" + choixcategorie + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        //item.setId(cursor.getString(0));
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                            /*ImageView img = (ImageView) findViewById(R.id.imagedelacategorie);
                                            img.setImageResource(R.drawable.ic_commerce);*/
     
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {
                        }
     
                        adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
                        listView = (ListView) findViewById(R.id.list_item);
                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
     
    /* j'utilisais ici la méthode onclicklistener */
     
                    } else if (lechoix == "" & choixcategorie != "Categorie" & choixville == "Ville") {
     
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where type=" + "'" + choixcategorie + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        //item.setId(cursor.getString(0));
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {
                        }
     
                        adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
                        listView = (ListView) findViewById(R.id.list_item);
                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                    } else if (lechoix == "" & choixcategorie == "Categorie" & choixville != "Ville") {
     
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where commune=" + "'" + choixville + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        //item.setId(cursor.getString(0));
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {
                        }
     
                        adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
                        listView = (ListView) findViewById(R.id.list_item);
                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                    } else if (lechoix == "" & choixcategorie != "Categorie" & choixville != "Ville") {
     
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where commune =" + "'" + choixville + "'" + " and type=" + "'" + choixcategorie + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        //item.setId(cursor.getString(0));
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {
                        }
     
                        adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
                        listView = (ListView) findViewById(R.id.list_item);
                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                    } else if (lechoix != "" & choixcategorie != "Categorie" & choixville == "Ville") {
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and type=" + "'" + choixcategorie + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        //item.setId(cursor.getString(0));
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {
                        }
     
                        adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
                        listView = (ListView) findViewById(R.id.list_item);
                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
     
                    } else if (lechoix != "" & choixcategorie == "Categorie" & choixville != "Ville") {
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and commune =" + "'" + choixville + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        //item.setId(cursor.getString(0));
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {
                        }
     
                        adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
                        listView = (ListView) findViewById(R.id.list_item);
                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
     
                    } else if (lechoix != "" & choixcategorie == "Categorie" & choixville == "Ville") {
     
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%')");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        //item.setId(cursor.getString(0));
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {
                        }
     
                        adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
                        listView = (ListView) findViewById(R.id.list_item);
                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                    } else if (lechoix == "" & choixcategorie == "Categorie" & choixville == "Ville") {
     
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        //item.setId(cursor.getString(0));
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {
                        }
     
                        adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
                        listView = (ListView) findViewById(R.id.list_item);
                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
     
                break;
     
                }
            }
     
     
        }
    }
    Adaptater

    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
     
     
    package com.cyatophilum.projetmenu;
     
    import android.app.Activity;
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
     
    import org.w3c.dom.Text;
     
    import java.util.ArrayList;
    import java.util.List;
     
    /**
     * Created by duyhoang on 11/30/2015.
     */
    public class Adapter extends ArrayAdapter<Item> {
        private Activity activity;
        int id;
        ArrayList<Item> items;
        public Adapter(Activity context, int resource, ArrayList<Item> objects) {
            super(context, resource, objects);
            this.activity=context;
            this.id=resource;
            this.items=objects;
        }
     
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView==null){
                LayoutInflater inflater=activity.getLayoutInflater();
                convertView=inflater.inflate(id,null);
            }
            Item item=items.get(position);
     
            TextView tv_type= (TextView) convertView.findViewById(R.id.tv_type);
            TextView tv_nom= (TextView) convertView.findViewById(R.id.tv_nom);
     
     
            tv_type.setText(item.getType());
            tv_nom.setText(item.getNom());
     
            return convertView;
        }
    }
    DatabaseHelper
    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
     
     
    package com.cyatophilum.projetmenu;
     
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteException;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;
     
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.sql.SQLException;
     
    /**
     * Created by duyhoang on 11/30/2015.
     */
    public class DatabaseHelper extends SQLiteOpenHelper {
        private static String DB_Path = "/data/data/com.cyatophilum.projetmenu/";
        private static String DB_Name = "my_database.sqlite";
        private SQLiteDatabase myDatabase;
        private final Context myContext;
     
        public DatabaseHelper(Context context) {
            super(context, DB_Name, null, 1);
            this.myContext = context;
        }
     
        @Override
        public void onCreate(SQLiteDatabase db) {
     
        }
     
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     
        }
     
        private boolean checkDatabase() {
            SQLiteDatabase checkDB = null;
            try {
                String myPath = DB_Path + DB_Name;
                checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
            } catch (SQLiteException e) {
     
            }
            if (checkDB != null) checkDB.close();
            return checkDB != null ? true : false;
        }
        private void copyDatabase() throws IOException{
            InputStream myInput=myContext.getAssets().open(DB_Name);
            String outFileName=DB_Path+DB_Name;
            OutputStream myOutput=new FileOutputStream(outFileName);
            byte[] buffer=new byte[1024];
            int length;
            while((length =myInput.read(buffer))>0){
                myOutput.write(buffer,0,length);
            }
            myOutput.flush();
            myOutput.close();
            myInput.close();
        }
        public void openDatabase() throws SQLException{
            String myPath=DB_Path+DB_Name;
            myDatabase=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
        }
        public void ExeSQLData(String sql) throws SQLException{
            myDatabase.execSQL(sql);
        }
        public Cursor QueryData(String query) throws SQLException{
            return myDatabase.rawQuery(query,null);
        }
     
        @Override
        public synchronized void close() {
            if (myDatabase !=null)
                myDatabase.close();
            super.close();
        }
        public void checkAndCopyDatabase(){
            boolean dbExist=checkDatabase();
            if (dbExist) {
                Log.d("TAG","Database already exist");
            }else{
                this.getReadableDatabase();
                try {
                    copyDatabase();
                }catch (IOException e){
                    Log.d("TAG","Error copying database");
                }
            }
        }
    }
    Item

    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
     
     
    package com.cyatophilum.projetmenu;
     
    public class Item {
        private String id;
        private String title;
        private String content;
        private String type;
        private String type_detail;
        private String nom;
        private String adresse;
        private String commune;
        private String telephone;
        private String email;
        private String siteweb;
        private String facebook;
        private String classement;
        private String ouverture;
        private String tarifsencl;
        private String tarifsmin;
        private String tarifsmax;
     
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
     
        public String getType() {
            return type;
        }
        public void setType(String type) {
            this.type = type;
        }
     
        public String getNom() {
            return nom;
        }
        public void setNom(String nom) {
            this.nom = nom;
        }
     
     
    }

  7. #7
    Membre confirmé

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Août 2014
    Messages
    262
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 30
    Localisation : Burkina Faso

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Finance

    Informations forums :
    Inscription : Août 2014
    Messages : 262
    Points : 634
    Points
    634
    Par défaut
    Déjà en ce qui concerne la ListView de ton Activity, je vois qu'à chaque fois que tu as besoin

    de l'afficher tu créer une nouvelle inflation. Ce qui, de mon point de vu, n'est pas optimisé et est source d'erreurs. Je

    propose d'initialiser une seul fois ta listView dans la méthode onCreate(...), en appliquant du même coup

    l'écouteur à travers listView.setOnItemClickListener(...). Plutard quand on aura besoin d'afficher

    la liste on change juste son Adapter avec listView(nouveau_adapter). La liste ne change pas, c'est plutôt

    les données(l'Adapter) qui change à chaque fois !
    Aujourd'hui apprenant, demain appreneur.
    N'accuse pas le puits d'être trop profond,
    c'est peut-être ta corde qui est trop courte

  8. #8
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2015
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2015
    Messages : 67
    Points : 108
    Points
    108
    Par défaut
    J'ai effectué les changements, du coup voila le code. Mais ça ne marche pas pourtant je ne comprends pas j'ai bien mit dans le oncreate
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
     
                    Toast.makeText(ButtonRecherche.this, "Position :", Toast.LENGTH_LONG).show();
                }
            });
    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
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
     
     
    public class ButtonRecherche extends AppCompatActivity implements View.OnClickListener {
        private ImageButton retour = null;
        private Spinner Categorie, Ville = null;
        ListView listView;
        private DatabaseHelper dbHelper;
        Adapter adapter;
        ArrayList<Item> arrayList = new ArrayList<Item>();
        ImageButton recherche = null;
        EditText Choixnom;
     
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_recherche);
     
            dbHelper = new DatabaseHelper(this);
            try {
                dbHelper.checkAndCopyDatabase();
                dbHelper.openDatabase();
            } catch (SQLException e) {
     
            }
     
            recherche = (ImageButton) findViewById(R.id.recherchons);
            recherche.setOnClickListener(this);
     
            Categorie = (Spinner) findViewById(R.id.spinner1);
            Ville = (Spinner) findViewById(R.id.spinner2);
            List<String> exemple1 = new ArrayList<String>();
            List<String> exemple2 = new ArrayList<String>();
     
            exemple1.add("Categorie");
            exemple1.add("Commerce et service");
            exemple1.add("Dégustation");
            exemple1.add("Equipement");
            exemple1.add("Hébergement collectif");
            exemple1.add("Hébergement locatif");
            exemple1.add("Hôtellerie");
            exemple1.add("Hôtellerie plein air");
            exemple1.add("Patrimoine culturel");
            exemple1.add("Patrimoine naturel");
            exemple1.add("Restauration");
     
            exemple2.add("Ville");
            exemple2.add("Lyon 2ème");
            exemple2.add("Lyon 1er");
            exemple2.add("Lyon 3ème");
     
            ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, exemple1);
            ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, exemple2);
            //Le layout par defaut est android.R.layout.simple_spinner_dropdown_item
            adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            Ville.setAdapter(adapter2);
            Categorie.setAdapter(adapter1);
     
            retour = (ImageButton) findViewById(R.id.retour);
            retour.setOnClickListener(this);
     
            adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
            listView = (ListView) findViewById(R.id.list_item);
            listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
     
     
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
     
                    Toast.makeText(ButtonRecherche.this, "Position :", Toast.LENGTH_LONG).show();
                }
            });
     
        }
     
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.retour:
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                    break;
     
                case R.id.recherchons:
     
                    arrayList.clear();
                    String choixcategorie = Categorie.getSelectedItem().toString();
                    String choixville = Ville.getSelectedItem().toString();
                    String lechoix = "";
                    Choixnom = (EditText) findViewById(R.id.choixx);
                    lechoix = Choixnom.getText().toString();
     
                    if (lechoix != "" & choixcategorie != "Categorie" & choixville != "Ville") {
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and commune =" + "'" + choixville + "'" + " and type=" + "'" + choixcategorie + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
     
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {                    }
                        listView.setAdapter(adapter);
     
                    } else if (lechoix == "" & choixcategorie != "Categorie" & choixville == "Ville") {
     
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where type=" + "'" + choixcategorie + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {                    }
     
                        listView.setAdapter(adapter);
     
                    } else if (lechoix == "" & choixcategorie == "Categorie" & choixville != "Ville") {
     
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where commune=" + "'" + choixville + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {                    }
     
                        listView.setAdapter(adapter);
     
     
                    } else if (lechoix == "" & choixcategorie != "Categorie" & choixville != "Ville") {
     
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where commune =" + "'" + choixville + "'" + " and type=" + "'" + choixcategorie + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {                    }
     
                        listView.setAdapter(adapter);
     
     
                    } else if (lechoix != "" & choixcategorie != "Categorie" & choixville == "Ville") {
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and type=" + "'" + choixcategorie + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {                    }
     
                        listView.setAdapter(adapter);
     
     
                    } else if (lechoix != "" & choixcategorie == "Categorie" & choixville != "Ville") {
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and commune =" + "'" + choixville + "'");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {                    }
     
                        listView.setAdapter(adapter);
     
     
                    } else if (lechoix != "" & choixcategorie == "Categorie" & choixville == "Ville") {
     
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%')");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {                    }
     
                        listView.setAdapter(adapter);
     
                    } else if (lechoix == "" & choixcategorie == "Categorie" & choixville == "Ville") {
     
                        try {
                            Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database");
                            if (cursor != null) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        Item item = new Item();
                                        item.setType(cursor.getString(1));
                                        item.setNom(cursor.getString(2));
                                        arrayList.add(item);
                                    } while (cursor.moveToNext());
                                }
                            }
                        } catch (SQLException e) {                    }
     
                        listView.setAdapter(adapter);
     
                    }
                break;
            }
     
     
        }
     
    }

  9. #9
    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
    Ca a l'air mieux en effet.

    Par contre, je ne comprends pas certaines parties du code:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
     case R.id.retour:
                        Intent intent = new Intent(this, MainActivity.class);
                        startActivity(intent);
                        break;
    C'est pour "revenir" à l'activité principale ? Dans ce cas , je pense que tu devrais plutôt utiliser "finish()" (qui va demander au système de justement rappeler l'activité précédente).

    Attention à ce genre de code:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    private Spinner Categorie, Ville = null;
    Il y a deux chose qu'on n'aime pas trop en Java... la multiple déclaration, et le mauvais nommage.... un "membre" (variable ou fonction) doit toujours commencer par une minuscule pour les différencier avec le type. D'autre part l'affectation finale ne concerne *que* Ville... et =null ne sert à rien (on est certain que Java le fera, cela fait partie du contrat d'initialisation des références). Donc préférer un truc genre:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    private Spinner spinnerCategorie;
    private Spinner spinnerVille;
    Meilleur nommage qui au passage permet de se souvenir que "Ville" n'est pas une ville mais un spinner

    Ensuite ce code:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
     if (lechoix != "" & choixcategorie != "Categorie" & choixville != "Ville")
    Est à priori toujours vrai.... != et == sont des tests de référence... il s'assurent que l'objet pointé (ici String) est le même par les deux références (les références sont donc égales).
    Ce n'est pas le cas ici... ce qu'on veut c'est que le contenu des deux objets soient le même. Il faut donc utiliser .equals()
    Attention aussi à "&" qui n'est *pas* l'opérateur booleen...
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    if (! "".equals(lechoix) && !"Categorie".equals(choixcategorie) && !"Ville".equals(choixville)) {
    Etrange que l'IDE n'ait pas affiché de gros "warning" sur ces lignes tout de même !


    Dans le code qui suit, tu remplis une liste, mais à aucun moment tu ne passe cette liste à l'adapter !
    Donc le setAdapter va réutiliser l'adapter existant, qui a toujours les mêmes données, et donc... ne rien faire du tout au final !

    Pour finir sur l'activité, deux conseils:
    Même si les exceptions (SQLException ici) ne sont jamais supposées se produire... il faut faire quelque chose dans le catch (d'ailleurs l'IDE propose de faire des warnings pour les catch vide, c'est une bonne idée de les activer).
    Un Log de l'exception suffit genre:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    Log.e("MonActivite","Impossible de récupérer les données pour "+choixville+" ou bien "+choixcategorie,e);
    L'important est un message cohérent (en fonction de l'endroit) avec les données, et l'exception en dernier paramètre. Et bien sur Log.e histoire de bien dire que c'est une erreur.

    La construction "manuelle" de SQL incorporant des paramètres choisis par l'utilisateur est fortement déconseillée.
    (essaye d'utiliser un nom de ville avec ' par exemple).
    Il existe des moyen de passer des paramètres aux requêtes SQL, il *faut* les utiliser.

    Au passage, il semble que "Item" ne soit pas complet, il manque un tas de getter/setter (tous les IDE ont une option de génération automatique de ceux-ci si besoin).


    Et un conseil général de séparation de code:
    Les fonctions de requête database devraient faire partie d'une classe à part.... ItemDAO par exemple, qui contiendrait le pointeur sur la base de donnée (SQLiteDatabase), et qui serait référencé par l'activité. Ca permet de "clarifier" le code, et souvent de factoriser des trucs (là en l'occurence, les tests sur choixville / categorie etc... sont des paramètre d'une fonction qui fait des requêtes plus ou moins similaire en fonction de ces paramètres, l'activité elle s'en fiche éperdument, et veux juste transformer la liste d'item reçue par le DAO en adapter pour la liste.
    (ce qui permet au passage de faire un DAO de test qui renvoie des objets de test et ainsi séparer la validation de l'interface de la validation de la logique interne).
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  10. #10
    Membre habitué
    Inscrit en
    Décembre 2007
    Messages
    94
    Détails du profil
    Informations personnelles :
    Âge : 36

    Informations forums :
    Inscription : Décembre 2007
    Messages : 94
    Points : 134
    Points
    134
    Par défaut
    Bonjour, peux tu nous donner le contenu de ton layout custom_list_item ?

  11. #11
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2015
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2015
    Messages : 67
    Points : 108
    Points
    108
    Par défaut
    Nicroman merci des conseils, par contre pour les requêtes SQL, elles fonctionnent bien, en fonction du remplissage ou non du champ recherche, du choix de catégorie et de ville dans le spinner. Si rien n'est touché, j'aurais toute la base, si je modifie les 3 paramètres alors je n'aurai que quelques éléments. Tu penses que ça peut être ça qui me bloque pour cliquer sur un item car je n'y arrive toujours pas

    Voici la layout principal et celui du custom. J'ai juste rajouté 1 image à la place du numéro qu'on peut voir sur l'écran et un boutton sur la droite pour chaque item.

    principal

    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
     
     
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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.cyatophilum.projetmenu.Button1Activity"
        android:orientation="vertical"
        android:weightSum="1">
     
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="1">
     
            <ImageButton
                android:id="@+id/retour"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_retour"
                android:background="#CC0000"
                android:clickable="true" />
     
            <TextView
                android:text="@string/Recherche"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:background="#CC0000"
                android:layout_height="match_parent"
                android:layout_width="match_parent"
                android:paddingTop="1dp"
                android:paddingBottom="10dp"
                android:gravity="center"
                android:id="@+id/t" />
        </LinearLayout>
     
        <View
            android:layout_width="fill_parent"
            android:layout_height="5dp"
            android:background="@color/black"/>
        <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
            <EditText
                android:id="@+id/choixx"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:hint="@string/Recherche2"
                android:textSize="30sp"
                android:layout_weight="0.92"
                android:singleLine="true" />
            <ImageButton
                android:id="@+id/recherchons"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:src="@drawable/loupe_recherche"
                android:background="#CC0000"
                android:layout_weight="0.04"
                android:clickable="true" />
        </LinearLayout>
        <View
            android:layout_width="fill_parent"
            android:layout_height="5dp"
            android:background="@color/black"/>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <Spinner
                android:id="@+id/spinner1"
                android:layout_width="0dp"
                android:layout_weight="0.5"
                android:layout_height="wrap_content">
            </Spinner>
            <Spinner
                android:id="@+id/spinner2"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.5">
            </Spinner>
        </LinearLayout>
     
        <ListView
            android:id="@+id/list_item"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/choixxx"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">
     
        </ListView>
    </LinearLayout>
    Custom :

    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
     
     
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_margin="2dp"
        android:background="#CC0000"
        android:orientation="horizontal">
     
        <ImageView
            android:id="@+id/imagedelacategorie"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_margin="1dp"
            android:src="@drawable/bloggif_569907e24c753"
            android:background="#CC0000"
            android:clickable="true" />
     
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:orientation="vertical">
     
            <TextView
                android:id="@+id/tv_nom"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:textSize="15dp"
                android:textColor="#FFFF"
                android:text="Type"
                android:layout_weight="1" />
     
            <TextView
                android:id="@+id/tv_type"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Nom"
                android:textSize="15dp"
                android:textColor="#FFFF"
                android:gravity="center_vertical"
                android:layout_weight="1" />
        </LinearLayout>
     
        <ImageButton
            android:id="@+id/boutonplusdetails"
            android:layout_width="45dp"
            android:layout_height="50dp"
            android:layout_margin="25dp"
            android:gravity="center"
            android:background="#CC0000"
            android:src="@drawable/ic_exit_to_app_white_18dp" />
    </LinearLayout>

  12. #12
    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
    J'ai pas dit que ça ne fonctionnait pas... juste que ce code là par exemple:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    Cursor cursor = dbHelper.QueryData("select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and commune =" + "'" + choixville + "'" + " and type=" + "'" + choixcategorie + "'")
    Va crasher dès que "lechoix" contient le caractère ' .... (ou choixville ou choixcategorie).

    Maintenant ma remarque concernant la séparation de code est plus de nature "structurelle" du programme:
    INTERFACE <= Liste de "Item" => DAO <= Cursor => Database


    Dans les requêtes que tu fais je vois ça:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    "select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and commune =" + "'" + choixville + "'" + " and type=" + "'" + choixcategorie + "'"
    "select id,type,nom from my_database" + " where type=" + "'" + choixcategorie + "'"
    "select id,type,nom from my_database" + " where commune=" + "'" + choixville + "'"
    "select id,type,nom from my_database" + " where commune =" + "'" + choixville + "'" + " and type=" + "'" + choixcategorie + "'"
    "select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%') and commune =" + "'" + choixville + "'";
    "select id,type,nom from my_database" + " where upper(nom) like upper('" + lechoix + "%')
    "select id,type,nom from my_database"
    (tiens au passage une table qui se nomme "my_database" ?
    Bon bref.... tout ça est fait à la main (danger), avec du code dupliqué à chaque fois (re-danger en cas de correction de bug), avec des colonnes choisies à la main (re-re-danger), etc...
    Un exemple de DAO (dans ton cas):

    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
     
    class ItemDAO
    {
          // les données locales
          private SQLiteDatabase db;
     
          // les constructeurs
          public ItemDAO(SQLiteDatabase db)
          {
                this.db = db;
          }
          public ItemDAO(SQLiteDatabaseHelper helper)
          {
                this(helper.getWritableDatabase());
          }
     
          // les données "publiques"
          public static final String  TABLE = "my_database";  // <= sic ?
     
          public static final String  COL_ID = "id";
          public static final String  COL_TYPE = "type";
          public static final String  COL_NOM = "nom";
          public static final String  COL_COMMUNE = "commune";
     
          // quelques données privées utilisées partout...
          private static final String[] ALL_COLS = { COL_ID, COL_TYPE, COL_NOM, COL_COMMUNE };
     
          // le DAO ne *montre* pas que c'est une Database derrière... d'ailleurs le constructeur *devrait* prendre un contexte uniquement
          // il renvoit juste une liste d'items....
          public List<Item> getItems(String choixNom,  String choixVille,  String choixCategorie)
          {
                ArrayList<Item> ret = new ArrayList<Item>();
     
                // on construit la selection
                ArrayList<String> whereArgs = new ArrayList<String>(3);
                StringBuilder whereClause = new StringBuilder();
     
                // la selection se fait simplement par "rajout" des options dans les builders & arguments...
                if (choixNom != null && choixNom.length() > 0) {
                     if (whereClause.length() > 0) whereClause.append(" and ");  // <= pas nécessaire, mais permet d'être cohérent avec les autres options, 
                     whereClause.append("upper(").append(COL_NOM).append(") like ?"); // <= le ? va etre remplacer par le paramètre
                     whereArgs.add(choixNom.toUpper(Locale.getDefault())+"%");
                }
                if (choixVille != null && choixVille.length() > 0 && !"Ville".equals(choixVille)) {   // <= ça se passera comment en "allemand" ?
                     if (whereClause.length() > 0) whereClause.append(" and ");
                     whereClause.append(COL_COMMUNE).append(" = ?");
                     whereArgs.add(choixVille);
                } 
                if (choixCategorie!= null && choixCategorie.length() > 0 && !"Categorie".equals(choixCategorie)) {   // <= ça se passera comment en "allemand" ?
                     if (whereClause.length() > 0) whereClause.append(" and ");
                     whereClause.append(COL_TYPE).append(" = ?");
                     whereArgs.add(choixCategorie);
                } 
     
                // on effectue la requete elle-même....
                Cursor c = null;
                try {
                    String selection = whereClause.length() == 0 ? null : whereClause.toString();
                    String[] selectionArgs = whereArgs.isEmpty() ? null : whereArgs.toArray(new String[arguments.size()]);
                     c = this.db.query(TABLE_NAME,ALL_COLS,selection,selectionArgs,null,null,null);
                     if (c.moveToFirst()) {
                        do {
                            Item item = itemFromCursor(c);
                            ret.add(item);
                        } while (c.moveToNext());
                     }
                } catch (SQLException ex) {
                     Log.e("ItemDAO","Failed to retrieve the list of items !",ex);
                } finally {
                     if (c != null) c.close();
                }
     
                return ret;
           }
     
           private static Item itemFromCursor(Cursor c)
           {
                 Item ret = new Item();
                 ret.setId(c.getLong(0));  // <= on connait les indices puisque c'est dans ALL_COLS
                 ret.setType(c.getString(1));
                 ret.setNom(c.getString(2));
                 ret.setCommune(c.getString(3));
                 return ret;
            }
    }
    Et voilà... coté activité, dans le onClick, tout devient plus simple (et moins surchargé):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
              case R.id.recherchons:
                    String choixCategorie = Categorie.getSelectedItem().toString();
                    String choixVille = Ville.getSelectedItem().toString();
                    String lechoix = ((EditText) findViewById(R.id.choixx)).getText().toString(); // sic
                    List<Item> items = new ItemDAO(dbHelper).getItems(lechoix,choixVille,choixCategorie);
                    Adapter newAdapter = new ItemAdapter(this,items); // j'ai pas bien compris comment tu peux créer un "Adapter" sans le surcharger ?
                    listView.setAdapter(newAdapter);
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  13. #13
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2015
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2015
    Messages : 67
    Points : 108
    Points
    108
    Par défaut
    C'est vrai que ça fait pas mal le ménage, je vais changer tout ça sinon tu aurais pas une idée pour pouvoir cliquer sur un item de la listview ?

  14. #14
    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
    Ben si... dans le onCreate... setOnListItemClickListener() et voila
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  15. #15
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2015
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2015
    Messages : 67
    Points : 108
    Points
    108
    Par défaut
    Ca ne marchait pas. Du coup j'ai tout recommencé le projet et trouvé une autre solution merci quand même à vous.

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

Discussions similaires

  1. Lancer une boucle pour repérer une erreur
    Par TomAlbus dans le forum MATLAB
    Réponses: 5
    Dernier message: 14/04/2011, 17h52
  2. Réponses: 3
    Dernier message: 29/03/2011, 20h38
  3. Appeler une fonction pour lancer une alerte javascript
    Par beegees dans le forum Langage
    Réponses: 1
    Dernier message: 09/01/2009, 16h10
  4. Réponses: 2
    Dernier message: 06/04/2006, 11h57

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