web-dev-qa-db-fra.com

Android AsyncTask [Impossible de créer un gestionnaire à l'intérieur du thread qui n'a pas appelé Looper.prepare ()]

J'ai créé un téléchargement d'image AsyncTask basé sur une fonction. Et après le téléchargement, j'obtiens cette erreur sur onPostExecute(). J'ai lu quelques réponses StackOverflow sur Runnable mais j'ai continué à obtenir l'erreur encore et encore malgré l'implémentation d'une solution différente.

Mon code:

class uploadFile extends AsyncTask<String, String, String> {
    private ProgressDialog pDialog;

    /**
     * --------------------------------------------------------------------
     * --------------------------------- Before starting background thread
     * Show Progress Dialog
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Uploading file");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * --------------------------------------------------------------------
     * --------------------------------- getting all recent articles and
     * showing them in listview
     */
    @Override
    protected String doInBackground(String... args) {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/mypic.png";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String serverResponseMessage = "";
        String urlString = "http://google.info/imgupl/index.php";
        try {
            // ------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(
                    existingFileName));
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + existingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // close streams
            Integer serverResponseCode = conn.getResponseCode();
            serverResponseMessage = conn.getResponseMessage();
            Toast.makeText(getApplicationContext(), serverResponseMessage,
                    Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(),
                    serverResponseCode.toString(), Toast.LENGTH_SHORT)
                    .show();
            Log.e("Debug", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        // ------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream(conn.getInputStream());

            while ((str = inStream.readLine()) != null) {
                Log.e("Debug", "Server Response " + str);
            }
            inStream.close();

        } catch (IOException ioex) {
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
        return null;
    }

    /**
     * --------------------------------------------------------------------
     * --------------------------------- After completing background task
     * Dismiss the progress dialog
     **/
    protected void onPostExecute(String args) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        MainActivity.this.runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

Mon logcat:

08-13 22:13:32.627: E/AndroidRuntime(9554): FATAL EXCEPTION: AsyncTask #1
08-13 22:13:32.627: E/AndroidRuntime(9554): Java.lang.RuntimeException: An error occured while executing doInBackground()
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Android.os.AsyncTask$3.done(AsyncTask.Java:200)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.Java:274)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Java.util.concurrent.FutureTask.setException(FutureTask.Java:125)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.Java:308)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Java.util.concurrent.FutureTask.run(FutureTask.Java:138)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.Java:1088)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:581)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Java.lang.Thread.run(Thread.Java:1019)
08-13 22:13:32.627: E/AndroidRuntime(9554): Caused by: Java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Android.os.Handler.<init>(Handler.Java:121)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Android.widget.Toast.<init>(Toast.Java:68)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Android.widget.Toast.makeText(Toast.Java:231)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at dev.google.imageupload.MainActivity$uploadFile.doInBackground(MainActivity.Java:128)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at dev.google.imageupload.MainActivity$uploadFile.doInBackground(MainActivity.Java:1)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Android.os.AsyncTask$2.call(AsyncTask.Java:185)
08-13 22:13:32.627: E/AndroidRuntime(9554):     at Java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.Java:306)
08-13 22:13:32.627: E/AndroidRuntime(9554):     ... 4 more

MODIFIÉ après la suggestion de zapl:

08-13 22:38:06.297: E/AndroidRuntime(11511): FATAL EXCEPTION: AsyncTask #1
08-13 22:38:06.297: E/AndroidRuntime(11511): Java.lang.RuntimeException: An error occured while executing doInBackground()
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Android.os.AsyncTask$3.done(AsyncTask.Java:200)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.Java:274)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Java.util.concurrent.FutureTask.setException(FutureTask.Java:125)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.Java:308)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Java.util.concurrent.FutureTask.run(FutureTask.Java:138)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.Java:1088)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:581)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Java.lang.Thread.run(Thread.Java:1019)
08-13 22:38:06.297: E/AndroidRuntime(11511): Caused by: Java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Android.os.Handler.<init>(Handler.Java:121)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Android.widget.Toast.<init>(Toast.Java:68)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Android.widget.Toast.makeText(Toast.Java:231)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at dev.google.imageupload.MainActivity$uploadFile.doInBackground(MainActivity.Java:128)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at dev.google.imageupload.MainActivity$uploadFile.doInBackground(MainActivity.Java:1)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Android.os.AsyncTask$2.call(AsyncTask.Java:185)
08-13 22:38:06.297: E/AndroidRuntime(11511):    at Java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.Java:306)
08-13 22:38:06.297: E/AndroidRuntime(11511):    ... 4 more
27
MrYanDao

Vous essayez de mettre à jour l'interface utilisateur à partir d'un thread d'arrière-plan. Déplacez le toast vers onPostExecute, qui s'exécute sur le thread d'interface utilisateur (recommandé), ou appelez runOnUiThread.

runOnUiThread(new Runnable() {
    public void run() {
        // runs on UI thread
    }
});
52
Tyler Treat

sur dev.shaunidiot.imageupload.MainActivity $ uploadFile.doInBackground (MainActivity.Java:128)

Vous pouvez utiliser le mécanisme de progression de AsyncTasks pour mettre à jour l'interface utilisateur de l'intérieur doInBackground pendant l'exécution de la tâche:

remplacer

Toast.makeText(getApplicationContext(), serverResponseMessage,
        Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
        serverResponseCode.toString(), Toast.LENGTH_SHORT)
        .show();

dans doInBackground avec

publishProgress(serverResponseMessage, serverResponseCode.toString());

et ajoutez ce qui suit à votre implémentation AsyncTask

@Override
protected void onProgressUpdate(String... values) {
    if (values != null) {
        for (String value : values) {
            // shows a toast for every value we get
            Toast.makeText(MainActivity.this, value, Toast.LENGTH_SHORT).show();
        }
    }
}

Vous avez déjà défini String comme type de progression dans AsyncTask<Params, Progress, Result> donc si vous voulez utiliser progress pour quelque chose de différent, vous pouvez essayer d'utiliser runOnUiThread mais je ne sais pas si cela fonctionnera.

7
zapl