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 :

listview dans un fragment


Sujet :

Composants graphiques Android

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Futur Membre du Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2015
    Messages
    4
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Cameroun

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2015
    Messages : 4
    Par défaut listview dans un fragment
    Bnonsoir, je suis un nouveau dans le developpement android et j'ai rencontré une erreur dans mon code ci-dessous au niveau du "this" et je ne sais pas comment résoudre. Merci de bien vouloir m'aider

    code:


    Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    package com.example.hp.fragments;
     
    import android.content.Context;
    import android.content.res.Resources;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;
     
    import com.example.hp.monapplication.Accueil;
    import com.example.hp.monapplication.R;
     
    import java.util.ArrayList;
     
    /**
     * Created by HP on 20/10/2015.
     */
    public class AccueilFragment extends Fragment {
     
     
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     
    // Inflate the layout for this fragment
            final View view = inflater.inflate(R.layout.accueil_fragment, container, false);
     
            ((Accueil) getActivity()).getSupportActionBar().setTitle("Accueil");
     
            ListView list = (ListView) view.findViewById(R.id.myList);
            list.setAdapter(new ListAdapter(this));
     
            return view;
     
        }
     
    }
     
    class SingleRow {
     
        String title;
        String description;
        String date;
        int    image;
     
        SingleRow(String title, String description, int image, String date) {
     
            this.title = title;
            this.description = description;
            this.image = image;
            this.date = date;
        }
    }
     
    class ListAdapter extends BaseAdapter {
     
        ArrayList<SingleRow> list;
        Context              context;
     
        ListAdapter(Context c) {
            context = c;
            list = new ArrayList<SingleRow>();
            Resources res = c.getResources();
            String[] titles = res.getStringArray(R.array.titles);
            String[] descriptions = res.getStringArray(R.array.descriptions);
            int[] images = {R.drawable.home, R.drawable.historic, R.drawable.contact, R.drawable.search, R.drawable.africa, R.drawable.about};
            String[] dates = res.getStringArray(R.array.datePublication);
     
            for (int i = 0; i < 10; i++) {
     
                list.add(new SingleRow(titles[i], descriptions[i], images[i], dates[i]));
            }
        }
     
        @Override
        public int getCount() {
            return list.size();
        }
     
        @Override
        public Object getItem(int i) {
            return list.get(i);
        }
     
        @Override
        public long getItemId(int i) {
            return i;
        }
     
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
     
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View row = inflater.inflate(R.layout.affichageitem, viewGroup, false);
     
            TextView title = (TextView) row.findViewById(R.id.title);
            TextView description = (TextView) row.findViewById(R.id.description);
            ImageView image = (ImageView) row.findViewById(R.id.image);
            TextView date = (TextView) row.findViewById(R.id.date);
     
            SingleRow temp = list.get(i);
     
            title.setText(temp.title);
            description.setText(temp.description);
            image.setImageResource(temp.image);
            date.setText(temp.date);
     
            return row;
        }
    }

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

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

    Informations forums :
    Inscription : Août 2003
    Messages : 6 693
    Par défaut
    Bonjour,

    J'imagine que ton problème c'est le passage d'un context que tu passe habituellement avec this dans une activity ?
    il faut dans un fragment utiliser getActivity() à la place de this quand tu as besoin d'un context.
    Attention toutefois, getActivity() peut retourner null selon le moment ou tu vas l'appeler.
    Pry Framework php5 | N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  3. #3
    Futur Membre du Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2015
    Messages
    4
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Cameroun

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2015
    Messages : 4
    Par défaut Bonjour Grunk
    Bonjour Grunk,

    Je vais d'abord te remercier pour la réponse. Lorsque j'ai remplacé this par getActivity() ça ne plus afficher d'erreur mais quand je lance l'application elle plante. Je ne sais pas comment réparer ce problème là.

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

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

    Informations forums :
    Inscription : Août 2003
    Messages : 6 693
    Par défaut
    Pour ça il faut voir ce qui s'affiche dans le logcat. Il y'a en général un message d'erreur très clair qui permet de résoudre le problème.
    Pry Framework php5 | N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  5. #5
    Futur Membre du Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2015
    Messages
    4
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Cameroun

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2015
    Messages : 4
    Par défaut
    voici le message d'erreur qui s'affiche dans le logcat:

    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
    AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: com.example.hp.voxjeunesse, PID: 18174
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hp.voxjeunesse/com.example.hp.monapplication.Accueil}: java.lang.ArrayIndexOutOfBoundsException: length=6; index=6
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                at android.os.Handler.dispatchMessage(Handler.java:110)
                at android.os.Looper.loop(Looper.java:193)
                at android.app.ActivityThread.main(ActivityThread.java:5299)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
                at dalvik.system.NativeStart.main(Native Method)
         Caused by: java.lang.ArrayIndexOutOfBoundsException: length=6; index=6
                at com.example.hp.fragments.ListAdapter.<init>(AccueilFragment.java:74)
                at com.example.hp.fragments.AccueilFragment.onCreateView(AccueilFragment.java:33)
                at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1016)
                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1197)
                at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
                at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
                at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:511)
                at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
                at android.app.Activity.performStart(Activity.java:5274)
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
    ************at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
    ************at android.app.ActivityThread.access$800(ActivityThread.java:151)
    ************at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
    ************at android.os.Handler.dispatchMessage(Handler.java:110)
    ************at android.os.Looper.loop(Looper.java:193)
    ************at android.app.ActivityThread.main(ActivityThread.java:5299)
    ************at java.lang.reflect.Method.invokeNative(Native Method)
    ************at java.lang.reflect.Method.invoke(Method.java:515)
    ************at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
    ************at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
    ************at dalvik.system.NativeStart.main(Native Method)

  6. #6
    Expert confirmé

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

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

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Billets dans le blog
    3
    Par défaut
    C'est tout marqué:

    Caused by: java.lang.ArrayIndexOutOfBoundsException: length=6; index=6
    at com.example.hp.fragments.ListAdapter.<init>(AccueilFragment.java:74)
    On est donc dans le fichier AccueilFragment.java, ligne 74
    Dans le code d'initialisation de la classe ListAdapter ????? (je dis ???? parce-que avoir une classe dont le .java ne correspond pas est fortement déconseillé, voir interdit par java. D'après le code posté en premier message il semble effectivement que la classe en question soit "sortie" du fragment.. (la déclaration n'est pas statique à l'interieur de AcceuilFragment).
    On fait référence au 7ème élément d'un tableau (index=6) qui n'en contient que 6 (length=6).

    Je penche fortement pour le tableau "image"....

    Ce genre de code est fortement propice aux bugs soit-dit en passant... les 4 tableaux doivent obligatoirement avoir une taille de 10 (fixée dans le code) ce qui va fatalement ne pas être le cas à un moment du développement
    Je te conseille vivement de faire une autre approche moins "bug-prone".

    Par exemple:
    Construire la liste de "SimpleRow"... avec uniquement son titre (ou un identifiant peu-importe).
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    String[] titles = res.getStringArray(R.array.titles);
    SimpleRow[] rows = new SimpleRow[titles.length];
    for (int i = 0; (i < rows.length); ++i) 
        rows[i] = new SimpleRow(titles[i],context);
    Et dans la construction de SimpleRow, récupérer les éléments restants en fonction du title.
    R.drawable.#####
    R.string.desc_######
    R.string.date_###### <= int ? non ?

    Si la valeur n'est pas trouvée, utiliser une valeur par défaut pour l'élément. Resources.getIdentifier est utile dans ce cas.

    L'idéal serait que la liste initiale soit bien dans les ressources, mais ne soit pas traduite. (ça marche quand même si c'est traduit, mais on risque d'avoir des trucs bizarres dans les noms de ressource).

Discussions similaires

  1. Problème ListView dans un fragment
    Par Timoune007 dans le forum Composants graphiques
    Réponses: 7
    Dernier message: 19/09/2015, 17h05
  2. Problème de rafraîchissement de ListView dans un Fragment
    Par natalie75 dans le forum Composants graphiques
    Réponses: 0
    Dernier message: 03/05/2015, 12h59
  3. Android navigation drawer: comment placer un ListView dans un fragment ?
    Par bigbang84 dans le forum Composants graphiques
    Réponses: 2
    Dernier message: 14/08/2014, 22h44
  4. Mettre une ListView dans un fragment ?
    Par toufou dans le forum Composants graphiques
    Réponses: 13
    Dernier message: 01/02/2013, 22h04
  5. Réponses: 8
    Dernier message: 12/05/2006, 14h04

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