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 :

Mise à jour d'une ListView via MySQL


Sujet :

Composants graphiques Android

  1. #1
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2012
    Messages
    43
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2012
    Messages : 43
    Points : 29
    Points
    29
    Par défaut Mise à jour d'une ListView via MySQL
    Salut à tous,

    Plongé dans le développement de mon programme, je rencontre une erreur qui me semble pas vraiment parlant.

    Alors voici dans l'ordre mon logcat ainsi que le code java:

    Lorsque je clique sur l’élément de ma listview cela devrait me retourner les informations d'un contact, pour les mettre a jour.

    Étape 1:
    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
    11-29 07:15:32.342: W/dalvikvm(1091): threadid=1: thread exiting with uncaught exception (group=0x41465700)
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): FATAL EXCEPTION: main
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): android.os.NetworkOnMainThreadException
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at libcore.io.IoBridge.connect(IoBridge.java:112)
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at java.net.Socket.connect(Socket.java:842)
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
     
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
     
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at fr.paris8.contactcloud.JSONParser.makeHttpRequest(JSONParser.java:55)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at fr.paris8.contactcloud.MajContactActivity$Get_Detail_Contact$1.run(MajContactActivity.java:142)
     
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at android.os.Handler.handleCallback(Handler.java:730)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at android.os.Handler.dispatchMessage(Handler.java:92)
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at android.os.Looper.loop(Looper.java:137)
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at android.app.ActivityThread.main(ActivityThread.java:5103)
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at java.lang.reflect.Method.invokeNative(Native Method)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at java.lang.reflect.Method.invoke(Method.java:525)
     
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
     
     
    11-29 07:15:32.461: E/AndroidRuntime(1091): 	at dalvik.system.NativeStart.main(Native Method)
    Étape 2:
    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
    309
    310
    311
    312
    313
    314
    315
    316
    317
    public class  MajContactActivity  extends Activity {
     
        EditText txtNom;
        EditText txtPrenom;
        EditText txtNummobile;
        EditText txtNumfixe;
        EditText txtEmail;
        EditText txtAdresse;
        EditText txtProfession;
     
        Button btnSav;
        Button btnSup;
     
        String idcontact;
     
        // Progress Dialog
        private ProgressDialog pDialog;
     
        // JSON parser class
        JSONParser jsonParser = new JSONParser();
     
        // single contact url
        private static final String url_detail_contact = "http://10.0.2.2/etc/etc.php";
     
        // url to update contact
        private static final String url_update_contact = "http://10.0.2.2/etc/etc.php";
     
        // url to delete contact
        private static final String url_delete_contact = "http://10.0.2.2/etc/etc.php";
     
        // JSON Node names
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_CONTACT = "contact";
        private static final String TAG_IDCONTACT = "idcontact";
     
    	private static final String TAG_NOM = "nom";
    	private static final String TAG_PRENOM = "prenom";
    	private static final String TAG_NUMMOBILE = "nummobile";
    	private static final String TAG_NUMFIXE = "numfixe";
    	private static final String TAG_EMAIL = "email";
    	private static final String TAG_ADRESSE = "adresse";
    	private static final String TAG_PROFESSION = "profession";
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.maj_contact);
     
            // save button
            btnSav = (Button) findViewById(R.id.btnSav);
            btnSup = (Button) findViewById(R.id.btnSup);
     
            // getting contact details from intent
            Intent i = getIntent();
     
            // getting contact id (idcontact) from intent
            idcontact = i.getStringExtra(TAG_IDCONTACT);
     
            // Getting complete contact details in background thread
            new Get_Detail_Contact().execute();
     
            // save button click event
            btnSav.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
                    // starting background task to update contact
                    new Sav_Detail_Contact().execute();
                }
            });
     
            // Delete button click event
            btnSup.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
                    // deleting contact in background thread
                    new Sup_Contact().execute();
                }
            });
     
        }
     
        /**
         * Background Async Task to Get complete contact details
         * */
        class Get_Detail_Contact extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MajContactActivity.this);
                pDialog.setMessage("Chargement du contact. Veuillez patientez...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Getting contact details in background thread
             * */
            protected String doInBackground(String... params) {
     
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        // Check for success tag
                        int success;
                        try {
                            // Building Parameters
                            List<NameValuePair> params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair("idcontact", idcontact));
     
                            // getting contact details by making HTTP request
                            // Note that contact details url will use GET request
                            JSONObject json = jsonParser.makeHttpRequest(
                                    url_detail_contact, "GET", params);
     
                            // check your log for json response
                            Log.d("Detail contact unique", json.toString());
     
                            // json success tag
                            success = json.getInt(TAG_SUCCESS);
                            if (success == 1) {
                                // successfully received contact details
                                JSONArray contactObj = json
                                        .getJSONArray(TAG_CONTACT); // JSON Array
     
                                // get first contact object from JSON Array
                                JSONObject contact = contactObj.getJSONObject(0);
     
                                // contact with this idcontact found
                                // Edit Text
    							txtNom = (EditText) findViewById(R.id.inputNom);
    							txtPrenom = (EditText) findViewById(R.id.inputPrenom);
    							txtNummobile = (EditText) findViewById(R.id.inputNumMobile);
    							txtNumfixe = (EditText) findViewById(R.id.inputNumFixe);
    							txtEmail = (EditText) findViewById(R.id.inputEmail);
    							txtAdresse = (EditText) findViewById(R.id.inputAdresse);
    							txtProfession = (EditText) findViewById(R.id.inputProfession);
     
                                // display contact data in EditText
    							txtNom.setText(contact.getString(TAG_NOM));
    							txtPrenom.setText(contact.getString(TAG_PRENOM));
    							txtNummobile.setText(contact.getString(TAG_NUMMOBILE));
    							txtNumfixe.setText(contact.getString(TAG_NUMFIXE));
    							txtEmail.setText(contact.getString(TAG_EMAIL));
    							txtAdresse.setText(contact.getString(TAG_ADRESSE));
    							txtProfession.setText(contact.getString(TAG_PROFESSION));
     
                            }else{
                                // contact with idcontact not found
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once got all details
                pDialog.dismiss();
            }
        }
     
        /**
         * Background Async Task to  Save contact Details
         * */
        class Sav_Detail_Contact extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MajContactActivity.this);
                pDialog.setMessage("Sauvegarde du contact ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Saving contact
             * */
            protected String doInBackground(String... args) {
     
                // getting updated data from EditTexts
    			String nom = txtNom.getText().toString();
    			String prenom = txtPrenom.getText().toString();
    			String nummobile = txtNummobile.getText().toString();
    			String numfixe = txtNumfixe.getText().toString();
    			String email = txtEmail.getText().toString();
    			String adresse = txtAdresse.getText().toString();
    			String profession = txtProfession.getText().toString();
     
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
     
                params.add(new BasicNameValuePair(TAG_IDCONTACT, idcontact));
    			params.add(new BasicNameValuePair(TAG_NOM, nom));
    			params.add(new BasicNameValuePair(TAG_PRENOM, prenom));
    			params.add(new BasicNameValuePair(TAG_NUMMOBILE, nummobile));
    			params.add(new BasicNameValuePair(TAG_NUMFIXE, numfixe));
    			params.add(new BasicNameValuePair(TAG_EMAIL, email));
    			params.add(new BasicNameValuePair(TAG_ADRESSE, adresse));
    			params.add(new BasicNameValuePair(TAG_PROFESSION, profession));
     
                // sending modified data through http request
                // Notice that update contact url accepts POST method
                JSONObject json = jsonParser.makeHttpRequest(url_update_contact,
                        "POST", params);
     
                // check json success tag
                try {
                    int success = json.getInt(TAG_SUCCESS);
     
                    if (success == 1) {
                        // successfully updated
                        Intent i = getIntent();
                        // send result code 100 to notify about contact update
                        setResult(100, i);
                        finish();
                    } else {
                        // failed to update contact
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once contact uupdated
                pDialog.dismiss();
            }
        }
     
        /*****************************************************************
         * Background Async Task to Delete Product
         * */
        class Sup_Contact extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MajContactActivity.this);
                pDialog.setMessage("Suppression du contact...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Deleting contact
             * */
            protected String doInBackground(String... args) {
     
                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("idcontact", idcontact));
     
                    // getting contact details by making HTTP request
                    JSONObject json = jsonParser.makeHttpRequest(
                            url_delete_contact, "POST", params);
     
                    // check your log for json response
                    Log.d("Suppression du contact", json.toString());
     
                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // contact successfully deleted
                        // notify previous activity by sending code 100
                        Intent i = getIntent();
                        // send result code 100 to notify about contact deletion
                        setResult(100, i);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once contact deleted
                pDialog.dismiss();
     
            }
     
        }
    }

    Merci de votre aide.

  2. #2
    Expert éminent

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

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

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Oui tu te mélanges un peu les pinceaux dans les AsyncTask...

    Déjà l'utilisation d'AsyncTask permet de s'affranchir *entièrement* des appels à runOnUIThread !

    Une AsyncTask est donc décomposée comme suit:

    onPreExecute()
    Affichage de progressions optionelles, préparation des l'interface... Executée dans le thread UI.

    doInBackground()
    C'est ici que l'on va récupérer les données sur le serveur (directement, pas besoin de runnable / runOnUIThread, puisqu'on est déjà dans un thread à part).

    onProgressUpdate()
    C'est ici qu'on va afficher du feedback à l'utilisateur pendant le chargement. Executée dans le thread UI. Le feedback est fourni durant le doInBackground par des appels à postProgress().

    onPostExecute()
    On recoit ici les données retournées par doInBackground mais en étant à nouveau dans le UI thread, on peut donc mettre à jour l'interface.
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  3. #3
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2012
    Messages
    43
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2012
    Messages : 43
    Points : 29
    Points
    29
    Par défaut
    Salut merci de la réponse, euhh par contre je m’étais renseigné:

    Les méthodes:
    onPreExecute (appelée avant le traitement),
    onProgressUpdate (appelée lorsque vous souhaitez afficher sa progression) et
    onPostExecute (appelée après le traitement) sont optionnelles.

    Donc du coup l'erreur ne vient pas de ceux la, mais je ne vois pas d’où peut provenir l'erreur alors que je ne remarque aucune erreur au niveau du code.

  4. #4
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Points : 5 072
    Points
    5 072
    Par défaut
    Tu as le Thread graphique.
    Tu crées une AsyncTask pour faire ton traitement long dedans.
    Dans cette AsyncTask, tu crées un nouveau Runnable pour le traitement long (ce qui fait double emploi avec doInBackground).
    Tu demandes à l'AsyncTask d'exécuter ce Runnable dans le Thread graphique.
    Ca crash car tu fais un appel réseau sur le thread graphique.

    En somme, tu demandes à un Thread A de créer un Thread B.
    Tu demandes ensuite au Thread B de créer un Runnable R.
    Tu demandes ensuite à ce que le Runnable R soit exécuté dans le Thread A.
    => Ton AsyncTask et ton Runnable sont inutiles, tu peux directement écrire le code du doInBackground dans un onCreate/onResume, ce sera plus clair et ça reviendra au même

    Pour la résolution, c'est simple : tu fais en deux temps.
    Premièrement, l'AsyncTask récupère les infos dans son doInBackground (pas de Runnable ou de runOnUiThread).
    Deuxièmement, l'AsyncTask met à jour l'affichage avec les infos récupérées dans son onPostExecute, qui s'exécute dans le Thread graphique.
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

  5. #5
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2012
    Messages
    43
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2012
    Messages : 43
    Points : 29
    Points
    29
    Par défaut
    Salut merci de votre réponse alors j'essaye de modifier en fonction de ce que vous m'avez demander "A savoir retirer les Runnable ou de runOnUiThread" ,cependant j'ai une erreur que je ne comprends pas.

    Étape 1: 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
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    12-02 05:59:51.030: E/AndroidRuntime(1070): FATAL EXCEPTION: AsyncTask #2
     
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): java.lang.RuntimeException: An error occured while executing doInBackground()
     
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.os.AsyncTask$3.done(AsyncTask.java:299)
     
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at java.util.concurrent.FutureTask.run(FutureTask.java:239)
     
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
     
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
     
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at java.lang.Thread.run(Thread.java:841)
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:869)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.view.ViewGroup.invalidateChild(ViewGroup.java:4253)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.view.View.invalidate(View.java:10482)
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.widget.TextView.invalidateRegion(TextView.java:4591)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.widget.TextView.invalidateCursor(TextView.java:4534)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.widget.TextView.spanChange(TextView.java:7412)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:9103)
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:979)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:688)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:588)
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.text.Selection.setSelection(Selection.java:76)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.text.Selection.setSelection(Selection.java:87)
     
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:302)
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.widget.TextView.setText(TextView.java:3759)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.widget.TextView.setText(TextView.java:3629)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.widget.EditText.setText(EditText.java:80)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.widget.TextView.setText(TextView.java:3604)
     
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at fr.paris8.contactcloud.MajContactActivity$GetDetailContact.doInBackground(MajContactActivity.java:162)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at fr.paris8.contactcloud.MajContactActivity$GetDetailContact.doInBackground(MajContactActivity.java:1)
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at android.os.AsyncTask$2.call(AsyncTask.java:287)
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	at java.util.concurrent.FutureTask.run(FutureTask.java:234)
     
    12-02 05:59:51.030: E/AndroidRuntime(1070): 	... 4 more
    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
    public class  MajContactActivity  extends Activity {
     
        EditText txtNom;
        EditText txtPrenom;
        EditText txtNummobile;
        EditText txtNumfixe;
        EditText txtEmail;
        EditText txtAdresse;
        EditText txtProfession;
     
        Button btnSav;
        Button btnSup;
     
        String idCONTACT;
     
        // Progress Dialog
        private ProgressDialog pDialog;
     
        // JSON parser class
        JSONParser jsonParser = new JSONParser();
     
        // single contact url
        private static final String url_detail_contact = "etc";
     
        // url to update contact
        private static final String url_update_contact = "etc";
     
        // url to delete contact
        private static final String url_delete_contact = "etc";
     
        // JSON Node names
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_CONTACT = "personne";
        private static final String TAG_IDCONTACT = "idCONTACT";
     
    	private static final String TAG_NOM = "nom";
    	private static final String TAG_PRENOM = "prenom";
    	private static final String TAG_NUMMOBILE = "numero_mobile";
    	private static final String TAG_NUMFIXE = "numero_fixe";
    	private static final String TAG_EMAIL = "email";
    	private static final String TAG_ADRESSE = "adresse";
    	private static final String TAG_PROFESSION = "profession";
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.maj_contact);
     
            // save button
            btnSav = (Button) findViewById(R.id.btnSav);
            btnSup = (Button) findViewById(R.id.btnSup);
     
            // getting contact details from intent
            Intent i = getIntent();
     
            // getting contact id (idCONTACT) from intent
            idCONTACT = i.getStringExtra(TAG_IDCONTACT);
     
            // Getting complete contact details in background thread
            new GetDetailContact().execute();
     
            // save button click event
            btnSav.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
                    // starting background task to update contact
                    new SavDetailContact().execute();
                }
            });
     
            // Delete button click event
            btnSup.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
                    // deleting contact in background thread
                    new SupContact().execute();
                }
            });
     
        }
     
        /**
         * Background Async Task to Get complete contact details
         * */
        class GetDetailContact extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MajContactActivity.this);
                pDialog.setMessage("Chargement du contact. Veuillez patientez...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Getting contact details in background thread
             * */
            protected String doInBackground(String... params) {
     
                        // Check for success tag
                        int success;
                        try {
                            // Building Parameters
                            List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                            params1.add(new BasicNameValuePair("idCONTACT", idCONTACT));
     
                            // getting contact details by making HTTP request
                            // Note that contact details url will use GET request
                            JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1);
     
                            // check your log for json response
                            Log.d("Detail contact unique", json.toString());
     
                            // json success tag
                            success = json.getInt(TAG_SUCCESS);
                            if (success == 1) {
                                // successfully received contact details
                                JSONArray contactObj = json.getJSONArray(TAG_CONTACT); // JSON Array
     
                                // get first contact object from JSON Array
                                JSONObject contact = contactObj.getJSONObject(0);
     
                                // contact with this idCONTACT found
                                // Edit Text
    							txtNom = (EditText) findViewById(R.id.inputNom);
    							txtPrenom = (EditText) findViewById(R.id.inputPrenom);
    							txtNummobile = (EditText) findViewById(R.id.inputNumMobile);
    							txtNumfixe = (EditText) findViewById(R.id.inputNumFixe);
    							txtEmail = (EditText) findViewById(R.id.inputEmail);
    							txtAdresse = (EditText) findViewById(R.id.inputAdresse);
    							txtProfession = (EditText) findViewById(R.id.inputProfession);
     
                                // display contact data in EditText
    							txtNom.setText(contact.getString(TAG_NOM));
    							txtPrenom.setText(contact.getString(TAG_PRENOM));
    							txtNummobile.setText(contact.getString(TAG_NUMMOBILE));
    							txtNumfixe.setText(contact.getString(TAG_NUMFIXE));
    							txtEmail.setText(contact.getString(TAG_EMAIL));
    							txtAdresse.setText(contact.getString(TAG_ADRESSE));
    							txtProfession.setText(contact.getString(TAG_PROFESSION));
     
                            }else{
                                // contact with idCONTACT not found
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
     
    			return null;
            }
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once got all details
                pDialog.dismiss();
            }
        }
     
        /**
         * Background Async Task to  Save contact Details
         * */
        class SavDetailContact extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MajContactActivity.this);
                pDialog.setMessage("Sauvegarde du contact ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Saving contact
             * */
            protected String doInBackground(String... args) {
     
                // getting updated data from EditTexts
    			String nom = txtNom.getText().toString();
    			String prenom = txtPrenom.getText().toString();
    			String numero_mobile = txtNummobile.getText().toString();
    			String numero_fixe = txtNumfixe.getText().toString();
    			String email = txtEmail.getText().toString();
    			String adresse = txtAdresse.getText().toString();
    			String profession = txtProfession.getText().toString();
     
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
     
                params.add(new BasicNameValuePair(TAG_IDCONTACT, idCONTACT));
    			params.add(new BasicNameValuePair(TAG_NOM, nom));
    			params.add(new BasicNameValuePair(TAG_PRENOM, prenom));
    			params.add(new BasicNameValuePair(TAG_NUMMOBILE, numero_mobile));
    			params.add(new BasicNameValuePair(TAG_NUMFIXE, numero_fixe));
    			params.add(new BasicNameValuePair(TAG_EMAIL, email));
    			params.add(new BasicNameValuePair(TAG_ADRESSE, adresse));
    			params.add(new BasicNameValuePair(TAG_PROFESSION, profession));
     
                // sending modified data through http request
                // Notice that update contact url accepts POST method
                JSONObject json = jsonParser.makeHttpRequest(url_update_contact,"POST", params);
     
                // check json success tag
                try {
                    int success = json.getInt(TAG_SUCCESS);
     
                    if (success == 1) {
                        // successfully updated
                        Intent i = getIntent();
                        // send result code 100 to notify about contact update
                        setResult(100, i);
                        finish();
                    } else {
                        // failed to update contact
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once contact uupdated
                pDialog.dismiss();
            }
        }
     
        /*****************************************************************
         * Background Async Task to Delete Product
         * */
        class SupContact extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MajContactActivity.this);
                pDialog.setMessage("Suppression du contact...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Deleting contact
             * */
            protected String doInBackground(String... args) {
     
                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("idCONTACT", idCONTACT));
     
                    // getting contact details by making HTTP request
                    JSONObject json = jsonParser.makeHttpRequest(url_delete_contact, "POST", params);
     
                    // check your log for json response
                    Log.d("Suppression du contact", json.toString());
     
                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // contact successfully deleted
                        // notify previous activity by sending code 100
                        Intent i = getIntent();
                        // send result code 100 to notify about contact deletion
                        setResult(100, i);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once contact deleted
                pDialog.dismiss();
     
            }
     
        }
    }

  6. #6
    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
    Normal

    Toute la partie modification de l'interface doit être fait dans le onPostExecute.

    les méthodes sont certes optionnelles mais pas inutiles.

    Si tu relis mon post, il est bien marqué que la mise à jour de l'interface doit être faite dans le onPostExecute.
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  7. #7
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2012
    Messages
    43
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2012
    Messages : 43
    Points : 29
    Points
    29
    Par défaut
    Salut merci encore des précisions, alors voila ce que j'ai fais en fonction de ce que j'ai compris.

    Par contre je n'ai pas encore compilé ce code il s'agit de savoir si la démarche est la suivante ?

    Merci encore de vos précisions ainsi que l'aide apporté!!

    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
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maj_contact);
     
        // save button
        btnSav = (Button) findViewById(R.id.btnSav);
        btnSup = (Button) findViewById(R.id.btnSup);
     
        // Edit Text
        txtNom = (EditText) findViewById(R.id.inputNom);
        txtPrenom = (EditText) findViewById(R.id.inputPrenom);
        txtNummobile = (EditText) findViewById(R.id.inputNumMobile);
        txtNumfixe = (EditText) findViewById(R.id.inputNumFixe);
        txtEmail = (EditText) findViewById(R.id.inputEmail);
        txtAdresse = (EditText) findViewById(R.id.inputAdresse);
        txtProfession = (EditText) findViewById(R.id.inputProfession);
     
     
        // getting contact details from intent
        Intent i = getIntent();
     
        // getting contact id (idCONTACT) from intent
        idCONTACT = i.getStringExtra(TAG_IDCONTACT);
     
        // Getting complete contact details in background thread
        new GetDetailContact().execute();
     
        // save button click event
        btnSav.setOnClickListener(new View.OnClickListener() {
     
            @Override
            public void onClick(View arg0) {
                // starting background task to update contact
                new SavDetailContact().execute();
            }
        });
     
        // Delete button click event
        btnSup.setOnClickListener(new View.OnClickListener() {
     
            @Override
            public void onClick(View arg0) {
                // deleting contact in background thread
                new SupContact().execute();
            }
        });
     
    }
     
    /**
     * Background Async Task to Get complete contact details
     * */
    class GetDetailContact extends AsyncTask<String, String, String> {
     
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MajContactActivity.this);
            pDialog.setMessage("Chargement du contact. Veuillez patientez...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
     
        /**
         * Getting contact details in background thread
         * */
        protected String doInBackground(String... params) {
     
            return null;
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
     
     
    		// Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                        params1.add(new BasicNameValuePair("idCONTACT", idCONTACT));
     
    		// getting contact details by making HTTP request
                        // Note that contact details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1);
     
                        // check your log for json response
                        Log.d("Detail contact unique", json.toString());
     
                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received contact details
                            JSONArray personneObj = json.getJSONArray(TAG_CONTACT); // JSON Array
     
                            // get first contact object from JSON Array
                            JSONObject personne = personneObj.getJSONObject(0);
     
                            // contact with this idCONTACT found
     
    					// display contact data in EditText
                            txtNom.setText(personne.getString(TAG_NOM));
                            txtPrenom.setText(personne.getString(TAG_PRENOM));
                            txtNummobile.setText(personne.getString(TAG_NUMMOBILE));
                            txtNumfixe.setText(personne.getString(TAG_NUMFIXE));
                            txtEmail.setText(personne.getString(TAG_EMAIL));
                            txtAdresse.setText(personne.getString(TAG_ADRESSE));
                            txtProfession.setText(personne.getString(TAG_PROFESSION));
                        }else{
                            // contact with idCONTACT not found
                        }
    					} catch (JSONException e) {
                        e.printStackTrace();
                    }        
        }
    }

  8. #8
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Points : 5 072
    Points
    5 072
    Par défaut
    Toujours pas !

    Le traitement doit se faire dans le doInBackground.
    L'affichage (sa mise à jour) doit se faire dans le onPostExecute.

    Fait ton appel réseau dans le doInBackground, crée tes objets, tes machins tes bidules, et passe-les ensuite au onPostExecute via le fonctionnement naturel d'une AsyncTask. Fait ensuite les mise à jour de ton affichage dans le onPostExecute.

    Ps : ton code devrait compiler, mais va crasher au runtime avec une jolie NetworkOnMainThreadException.
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

  9. #9
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2012
    Messages
    43
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2012
    Messages : 43
    Points : 29
    Points
    29
    Par défaut
    Merci de ta réponse alors j'ai plusieurs questions ?

    Citation Envoyé par Hizin Voir le message
    Toujours pas !

    Le traitement doit se faire dans le doInBackground.
    L'affichage (sa mise à jour) doit se faire dans le onPostExecute.

    Fait ton appel réseau dans le doInBackground, crée tes objets, tes machins tes bidules, et passe-les ensuite au onPostExecute via le fonctionnement naturel d'une AsyncTask. Fait ensuite les mise à jour de ton affichage dans le onPostExecute.

    Ps : ton code devrait compiler, mais va crasher au runtime avec une jolie NetworkOnMainThreadException.

    1.)Fait ton appel réseau dans le doInBackground, : Qu'entends tu pars appel réseau, que je devrais faire dans le doInBackground.

    2.)crée tes objets, tes machins tes bidules, et passe-les ensuite au onPostExecute : Tu fais référence a cet portions de code que je devrais mettre dans le onPostExecute:

    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
    int success;
    	                try {
    	                    // Building Parameters
    	                    List<NameValuePair> params1 = new ArrayList<NameValuePair>();
    	                    params1.add(new BasicNameValuePair("idCONTACT", idCONTACT));
     
    			// getting contact details by making HTTP request
    	                    // Note that contact details url will use GET request
    	                    JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1);
     
    	                    // check your log for json response
    	                    Log.d("Detail contact unique", json.toString());
     
    	                    // json success tag
    	                    success = json.getInt(TAG_SUCCESS);
    	                    if (success == 1) {
    	                        // successfully received contact details
    	                        JSONArray personneObj = json.getJSONArray(TAG_CONTACT); // JSON Array
     
    	                        // get first contact object from JSON Array
    	                        JSONObject personne = personneObj.getJSONObject(0);
     
    	                        // contact with this idCONTACT found
     
    						// display contact data in EditText
    	                        txtNom.setText(personne.getString(TAG_NOM));
    	                        txtPrenom.setText(personne.getString(TAG_PRENOM));
    	                        txtNummobile.setText(personne.getString(TAG_NUMMOBILE));
    	                        txtNumfixe.setText(personne.getString(TAG_NUMFIXE));
    	                        txtEmail.setText(personne.getString(TAG_EMAIL));
    	                        txtAdresse.setText(personne.getString(TAG_ADRESSE));
    	                        txtProfession.setText(personne.getString(TAG_PROFESSION));
    	                    }else{
    	                        // contact with idCONTACT not found
    	                    }
    						} catch (JSONException e) {
    	                    e.printStackTrace();
    	                }
    Merci réellement de votre aide !!!

  10. #10
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Points : 5 072
    Points
    5 072
    Par défaut
    La ligne JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1); fait une requête HTTP vers "url_detail_contact", en utilisant le verbe GET avec les paramètres "params1".

    Cet appel réseau ne doit pas être réalisé dans le Thread graphique. De manière générale, faire une opération longue dans le thread graphique est une mauvaise pratique, quelle que soit la plate-forme. Android la sanctionne depuis HoneyComb par l'exception NetworkOnMainThreadException.

    Il est nécessaire que tu comprennes le code que tu utilises. Tu dois faire l'appel réseau et la conversion JSON => objets dans le doInBackground.
    Une fois que c'est fait, donne ces objets naturellement au onPostExecute avec le mécanisme d'une AsyncTask (lis sa documentation, au besoin). Enfin, dans le onPostExecute, mets à jour ton affichage (en prenant en compte la possibilité que l'appel réseau ne se soit pas bien déroulé).

    Comme seriné :
    - onPreExecute se déroule dans le Thread graphique, donc sert généralement à préparer le contexte et l'affichage pour l'utilisateur
    - doInBackground se déroule dans un Thread à part, et sert à faire les opérations longues (dans ton cas l'appel réseau et la transformation en objets)
    - onPostExecute se déroule dans le Thread graphique, donc sert généralement à mettre à jour l'affichage et faire signifier à l'utilisateur "j'ai terminé mon traitement"
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

  11. #11
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2012
    Messages
    43
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2012
    Messages : 43
    Points : 29
    Points
    29
    Par défaut
    Salut tous,

    Alors voila j'ai apporté quelque modif cet fois-ci, mais il y a un problème
    Sous eclipse, il me met une erreur concernant le void du Asynctask
    Alors qu'il ne devrait pas me le mettre je comprend pas cet erreur ?

    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
    class GetDetailContact extends AsyncTask<String, void, JSONObject> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MajContactActivity.this);
                pDialog.setMessage("Chargement du contact. Veuillez patientez...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Getting contact details in background thread
             * */
            protected JSONObject doInBackground(String... params) {
     
                        // Check for success tag
                        int success;
                        try {
                            // Building Parameters
                            List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                            params1.add(new BasicNameValuePair("idCONTACT", idCONTACT));
     
                            // getting contact details by making HTTP request
                            // Note that contact details url will use GET request
                            JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1);
     
                            // check your log for json response
                            Log.d("Detail contact unique", json.toString());
     
                            // json success tag
                            success = json.getInt(TAG_SUCCESS);
                            if (success == 1) {
                                // successfully received contact details
                                JSONArray personneObj = json.getJSONArray(TAG_CONTACT); // JSON Array
     
                                // get first contact object from JSON Array
                                JSONObject personne = personneObj.getJSONObject(0);
     
                                // contact with this idCONTACT found
     
                               return personne;
     
                            }else{
                                // contact with idCONTACT not found
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                return null;
            }
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(JSONObject personne) {
                // dismiss the dialog once got all details
                pDialog.dismiss();
     
                               // display contact data in EditText
                                txtNom.setText(personne.getString(TAG_NOM));
                                txtPrenom.setText(personne.getString(TAG_PRENOM));
                                txtNummobile.setText(personne.getString(TAG_NUMMOBILE));
                                txtNumfixe.setText(personne.getString(TAG_NUMFIXE));
                                txtEmail.setText(personne.getString(TAG_EMAIL));
                                txtAdresse.setText(personne.getString(TAG_ADRESSE));
                                txtProfession.setText(personne.getString(TAG_PROFESSION));
            }
        }

  12. #12
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Points : 5 072
    Points
    5 072
    Par défaut
    Pas de type primitif en générique.
    Les IDE sont parfois tord, mais la plupart du temps, ils ont raison.

    void => Void. Utilise l'objet, non le type primitif.
    En Java, tout type commençant pas une majuscule est dit primitif (int, double, long...), et tout type commençant par une majuscule est un objet (String, AsyncTask...).
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

  13. #13
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2012
    Messages
    43
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2012
    Messages : 43
    Points : 29
    Points
    29
    Par défaut
    Merci de ta réponse j'avais déjà essayé mais lorsque je fais cela
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    AsyncTask<String, Void, JSONObject>
    c'est dans mon
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    onPostExecute(JSONObject personne)
    que cet suite d'instruction est surligné en rouge je parle de cela
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    personne.getString(TAG_NOM)

  14. #14
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Points : 5 072
    Points
    5 072
    Par défaut
    Et que te dit-il ?
    Aider sans erreur, c'est difficile. Aider sans contexte, c'est généralement impossible.

    On va sortir la boule de cristal... Eclipse ne te dit-il pas "unhandled exception: JSONException" ?
    Si c'est le cas... ben gère ton exception proprement ^^"
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

  15. #15
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2012
    Messages
    43
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2012
    Messages : 43
    Points : 29
    Points
    29
    Par défaut
    Voila ce qu'il me dis : Unhandled exception type JSONException

    Ensuite il me propose de faire un
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Surround with try catch
    Mais lorsque je compile cela ne marche pas sa ne me retourne pas les informations du contact.

  16. #16
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Points : 5 072
    Points
    5 072
    Par défaut
    Je te suggère fortement d'apprendre les bases de Java avant de te mettre au développement Android.

    Ton problème à présent semble être une incompréhension du mécanisme des Exceptions.
    Voici la FAQ : http://java.developpez.com/faq/java/?page=exception
    Celle-ci devrait répondre à ces questions.
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

Discussions similaires

  1. [c# 2.0] Mise à jour d'une table via DataSet
    Par tscoops dans le forum ASP.NET
    Réponses: 4
    Dernier message: 04/01/2008, 13h52
  2. Mise à jour d'une date dans MySQL
    Par champijulie dans le forum JDBC
    Réponses: 6
    Dernier message: 07/02/2007, 17h02
  3. Mise à Jour d'une table via un Update (select)
    Par Arola78 dans le forum Requêtes et SQL.
    Réponses: 4
    Dernier message: 23/09/2006, 14h59
  4. Mise à Jour d'une table via un formulaire
    Par Arola78 dans le forum IHM
    Réponses: 5
    Dernier message: 05/09/2006, 10h48
  5. Mise à jour d'une controle via une classe.
    Par Andry dans le forum Delphi
    Réponses: 4
    Dernier message: 23/06/2006, 15h00

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