Jump to content

Comment bien utiliser AsyncTask ?


Jorodan

Recommended Posts

Salut les jeunes!

Je continue mon développement!

Ma dernier délire, récupérer un fichier XML sur le net. Donc j'aimerai attendre avec classe en prévenant l'utilisateur!

J'en suis venu à utiliser AsyncTask!

Voici mon code. Les commentaires expliquent ce que je veux faire.


   /**
    * Ma classe de gestion de travail en arrière plan.
    * @author Julien
    *
    */
   class LoadReseauxTask extends AsyncTask { 

       /**
        * Ici la méthode qui réalise le travail effectif : récupérer un fichier XML.
        */
       @Override 
       protected String doInBackground(String... urls) { 
           // Réalisation de la récupération avec HTTPGET.
           HttpClient client = new DefaultHttpClient();
           HttpGet getMethod = new HttpGet(urls[0]);
           ResponseHandler responseHandler = new BasicResponseHandler();

           // Mon fichier pour récupérer le XML
           String myXML = "";
           try {
               myXML = client.execute(getMethod,responseHandler);
           } catch (ClientProtocolException e) {
               e.printStackTrace();
           } catch (IOException e) {
               Toast.makeText(ChoixReseau.this, "Problème réseau + " /*+ t.getMessage()*/, 4000).show(); 
           }

           return myXML;
       } 

       // Pas encore utilisé
       protected void onProgressUpdate(Void inutilise) { 
       } 

       /**
        * La méthode en fin de traitement qui prévient l'utilisateur.
        * @param inutilise
        */
       protected void onPostExecute(Void inutilise) { 
         Toast 
           .makeText(ChoixReseau.this, "Fini !", Toast.LENGTH_SHORT) 
               .show(); 
       } 
   }

La classe est utilisée dans mon activité par ces lignes :

           LoadReseauxTask lrt = new LoadReseauxTask();
           lrt.execute();

Mon problème est que je ne comprends pas la syntaxe pour utiliser les paramètres.

Quelqu'un a une idée ?

Link to comment
Share on other sites

Alors dans ce cas là, comment je récupère mes informations en retour ???

Je ne suis qu'un mauvais dev, mais je dirais avec un assesseur ? Il me semble qu'un AsyncTask n'est qu'une classe avec gestion integrée des thread, un simple assesseur devrais te permettre de récupérer ta données.

A confirmer par un dev expérimenté ! :)

Link to comment
Share on other sites

Bien vu, je n'y avais pas pensé !!

La doc pour get() :

http://developer.android.com/intl/fr/reference/android/os/AsyncTask.html#get%28long,%20java.util.concurrent.TimeUnit%29

public final Result get (long timeout, TimeUnit unit)

Since: API Level 3

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result.

Parameters

timeout Time to wait before cancelling the operation.

unit The time unit for the timeout.

Returns

* The computed result.

Throws

CancellationException If the computation was cancelled.

ExecutionException If the computation threw an exception.

InterruptedException If the current thread was interrupted while waiting.

TimeoutException If the wait timed out.

Ca doit être ca :D

Merci

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...