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

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

Android Discussion :

Actualisation ProgressBar dans un thread


Sujet :

Android

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 30
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Points : 14
    Points
    14
    Par défaut Actualisation ProgressBar dans un thread
    Bonjour,


    Je débute en programmation Android et je suis bloqué sur le développement de mon application.
    Avant toute chose, je veux ouvrir un document Excel (.xls) et l'afficher directement sur mon application, pour cela je passe par un TableLayout et je parcours mon Excel pour remplir mon TableLayout de TextRow et TextView.
    Cette partie fonctionne, néanmoins le chargement de gros fichier prenant du temps je veux afficher une barre de progression en fonction d'où on en est dans le parcours du fichier Excel.
    Pour cela j'ai créer une progressBar initialisée à 0 et le maximum au nombre de ligne de mon fichier Excel.

    Je passe ensuite tout cela dans un thread et c'est là que ça se complique, les textview nécessitant de rappeler le thread UI ..

    J'ai en résultat l'affichage de mon tableau et de ma progressBar, mais seulement lorsque l'application a finit de parcourir mon tableau (quand c'est terminé quoi..). Donc j'ai toujours mon temps de chargement, et ma progressbar qui est soit à 0 soit complète..

    Voici mon code ci dessous en espérant que vous pourrez m'aider

    Bonne journée,


    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
     private void readExcelFile(final Context context, final String filepath) {
     
            new Thread(new Runnable() {
                public void run() {
     
                    if (!isExternalStorageAvailable() || isExternalStorageReadOnly())
                    {
                        Log.e(TAG, "Storage not available or read only");
                        return;
                    }
     
                    final int num_param = getNumberofRows(context,filepath);
                    final int num_col = getNumberofColumns(context, filepath);
     
                    ProgressHandler.post(new Runnable() {
                        public void run() {
                            progress_bar.setMax(num_param);
                            progress_bar.setProgress(0);
                        }
                    });
     
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                // Creating Input Stream
                                File file = new File(filepath);
                                FileInputStream myInput = new FileInputStream(file);
                                // Create a POIFSFileSystem object
                                POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
                                // Create a workbook using the File System
                                HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
                                // Get the first sheet from workbook
                                HSSFSheet mySheet = myWorkBook.getSheetAt(0);
                                /** We now need something to iterate through the cells.**/
                                Iterator rowIter = mySheet.rowIterator();
     
                                //réinitialise les vues et le tableau
                                mTableLayout.removeAllViews();
                                mTableColumn.removeAllViews();
                                mTableLayoutHeader.removeAllViews();
     
                                compt_header=0;
                                compt_col=0;
                                while(rowIter.hasNext()){
     
                                    //create a tablerow
                                    TableRow tr = new TableRow(getApplicationContext());
     
                                    //creation de la ligne
                                    HSSFRow myRow = (HSSFRow) rowIter.next();
                                    Iterator cellIter = myRow.cellIterator();
     
                                    //creation des cellules de la ligne
                                    while(cellIter.hasNext()){
                                        HSSFCell myCell = (HSSFCell) cellIter.next();
     
                                        //Create a textview.//
                                        TextView trCell = new TextView(getApplicationContext());
     
                                        //Set TextView text, color,size of text, size of cell//
                                        trCell.setText(String.valueOf(myCell));
                                        trCell.setTextSize(17);
     
                                        trCell.setGravity(Gravity.CENTER);
                                        trCell.setWidth(ColumnWidths[compt_col]);
                                        trCell.setHeight(20);
     
                                        if( compt_header==0  )//si 1ère ligne (=titre colonne)
                                        {
                                            trCell.setTextColor(WHITE);
                                            trCell.setBackgroundResource(R.drawable.cell_header);
                                            tr.addView(trCell);
                                        }
                                        else if (compt_header!=0)  //si pas 1ère ligne
                                        {
                                            if(compt_col == 0) //si 1ère colonne
                                            {
                                                trCell.setTextColor(WHITE);
                                                trCell.setBackgroundResource(R.drawable.cell_header);
                                                mTableColumn.addView(trCell);
     
                                            }
                                            else if (compt_col !=0 )// si pas 1ère colonne
                                            {
                                                trCell.setTextColor(BLACK);
                                                trCell.setBackgroundResource(R.drawable.cell_shape);
                                                tr.addView(trCell);
                                            }
                                        }
                                        compt_col++;
                                        //fin cellule
                                    }
     
                                    compt_col=0; //réinitialise à 0, on va à la ligne suivante => colonne=0
                                    if(compt_header==0) {
                                        compt_header++;
                                        mTableLayoutHeader.addView(tr); //Add tablerow to the tablelayout
                                    }
                                    else if(compt_header!=0) {
                                        compt_header++;
                                        mTableLayout.addView(tr); //Add tablerow to the tablelayout
     
                                    }
                                    //fin ligne
     
     
                                }
                                /**** Update the progress bar ****/
                                ProgressHandler.post(new Runnable() {
                                     public void run() {
                                         progress_bar.setProgress(compt_header);
                                     }
                                 });
     
                                //fin tableau
     
                           }catch (Exception e){e.printStackTrace(); }
                    }
                });
                }
            }).start();
     
        }

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

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

    Informations forums :
    Inscription : Août 2003
    Messages : 6 691
    Points : 20 222
    Points
    20 222
    Par défaut
    Ton thread ne sert à rien dans ton cas puisque toute la partie lourde de ton traitement est effectuée dans runOnUiThread c'est à dire sur le threadUI.
    Pour simplifier tu lance un thread qui lance du travail sur le thread ui => inutile.

    Le seul moment ou tu dois appeler runOnUiThread c'est pour mettre à jour ta progress bar et éventuellement d'autre éléments d'interface. Il ne faut surtout pas y effectuer de traitement lourd comme tu le fais.
    Pry Framework php5 | N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 30
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Points : 14
    Points
    14
    Par défaut
    Oui c'est ce que je me disais aussi .. Mais je ne vois pas comment faire étant donné que je fais mon traitement en même temps que mon affichage, donc j'ai besoin de faire le traitement dans le Thread UI pour venir construire mon tableau à l'écran

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

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

    Informations forums :
    Inscription : Août 2003
    Messages : 6 691
    Points : 20 222
    Points
    20 222
    Par défaut
    C'est bien le problème il faut en principe dissocier le traitement long de la partie affichage

    Dans ton cas , je pense (à tester) que tu dois pouvoir construire dynamiquement ton interface (les new TableRow() , new TextView() ...) dans ton thread. Et niquement appeler le runOnUiThread au moment ou tu viens mettre à jour sois la progressbar sois mTableLayout
    Pry Framework php5 | N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  5. #5
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 30
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Points : 14
    Points
    14
    Par défaut
    Du coup j'ai mis tout ce qu'il fallait dans le thread UI pour actualiser l'affichage et ça marche ! Le rendu est saccadé mais c'est du aux nombreux appels de thread UI je pense. Je suis pas très fier de mon code parce que je fais appel au thread UI 5 fois mais bon ..
    En tout cas merci de ton aide

    Je laisse la solution ci-dessous quand même :
    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
    private void readExcelFile(final Context context, final String filepath) {
     
            new Thread(new Runnable() {
                public void run() {
                try {
     
                    if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
                        Log.e(TAG, "Storage not available or read only");
                        return;
                    }
     
                    final int num_param = getNumberofRows(context, filepath);
                    final int num_col = getNumberofColumns(context, filepath);
     
                    ProgressHandler.post(new Runnable() {
                        public void run() {
                            progress_bar.setMax(num_param);
                            progress_bar.setProgress(0);
                        }
                    });
     
     
                    // Creating Input Stream
                    File file = new File(filepath);
                    FileInputStream myInput = new FileInputStream(file);
                    // Create a POIFSFileSystem object
                    POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
                    // Create a workbook using the File System
                    HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
                    // Get the first sheet from workbook
                    HSSFSheet mySheet = myWorkBook.getSheetAt(0);
                    /** We now need something to iterate through the cells.**/
                    Iterator rowIter = mySheet.rowIterator();
     
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //réinitialise les vues et le tableau
                            mTableLayout.removeAllViews();
                            mTableColumn.removeAllViews();
                            mTableLayoutHeader.removeAllViews();
                        }
                    });
     
                    compt_header = 0;
                    compt_col = 0;
                    while (rowIter.hasNext()) {
     
                        //create a tablerow
                        final TableRow tr = new TableRow(getApplicationContext());
     
                        //creation de la ligne
                        HSSFRow myRow = (HSSFRow) rowIter.next();
                        Iterator cellIter = myRow.cellIterator();
     
                        //creation des cellules de la ligne
                        while (cellIter.hasNext()) {
                            HSSFCell myCell = (HSSFCell) cellIter.next();
                            //Create a textview.//
                            final TextView trCell = new TextView(getApplicationContext());
     
                            trCell.setText(String.valueOf(myCell));
                            trCell.setTextSize(17);
                            trCell.setGravity(Gravity.CENTER);
                            trCell.setWidth(ColumnWidths[compt_col]);
                            trCell.setHeight(20);
     
                            if (compt_header == 0)//si 1ère ligne (=titre colonne)
                            {
                                trCell.setTextColor(WHITE);
                                trCell.setBackgroundResource(R.drawable.cell_header);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tr.addView(trCell);
                                    }
                                });
                            } else if (compt_header != 0)  //si pas 1ère ligne
                            {
                                if (compt_col == 0) //si 1ère colonne
                                {
                                    trCell.setTextColor(WHITE);
                                    trCell.setBackgroundResource(R.drawable.cell_header);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                             mTableColumn.addView(trCell);
                                        }
                                    });
     
                                } else if (compt_col != 0)// si pas 1ère colonne
                                {
                                    trCell.setTextColor(BLACK);
                                    trCell.setBackgroundResource(R.drawable.cell_shape);
                                    runOnUiThread(new Runnable() {
                                          @Override
                                          public void run() {
                                                tr.addView(trCell);
                                          }
                                    });
                                }
                            }
                            compt_col++;
                            //fin cellule
                        }
     
                        compt_col = 0; //réinitialise à 0, on va à la ligne suivante => colonne=0
                        if (compt_header == 0) {
                            compt_header++;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                     mTableLayoutHeader.addView(tr); //Add tablerow to the tablelayout
                                }
                            });
                        } else if (compt_header != 0) {
                            compt_header++;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mTableLayout.addView(tr); //Add tablerow to the tablelayout
                                }
                            });
                        }
                        //fin ligne
     
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                        /**** Update the progress bar ****/
                        ProgressHandler.post(new Runnable() {
                            public void run() {
                                // progress_bar.incrementProgressBy(1);
                                progress_bar.setProgress(compt_header);
                            }
                        });
                            }
                        });
     
                        //fin tableau
                        wbToSave = myWorkBook;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
     
        }

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

Discussions similaires

  1. [AC-2003] Lancer mon formulaire d'attente (ProgressBar) dans un thread
    Par dut-dut dans le forum VBA Access
    Réponses: 3
    Dernier message: 02/09/2011, 13h31
  2. ProgressBar dans un Thread
    Par kelkar dans le forum Macros et VBA Excel
    Réponses: 2
    Dernier message: 22/08/2007, 11h30
  3. [MFC] afficher une ProgressBar dans une barre d'etat
    Par guillaume21 dans le forum MFC
    Réponses: 5
    Dernier message: 30/03/2007, 11h16
  4. erreur d'un timer declaré dans un thread
    Par hak5 dans le forum C++Builder
    Réponses: 2
    Dernier message: 03/04/2004, 09h20
  5. Gestion des message windows dans les threads
    Par billyboy dans le forum Windows
    Réponses: 5
    Dernier message: 06/10/2003, 17h25

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