Android AsyncTask【在未调用Looper.prepare()的线程中无法创建处理程序】

29
我已经基于一个函数创建了一个图片上传的AsyncTask。上传完成后,在onPostExecute()中出现了以下错误。我查看了一些 StackOverflow 上的关于Runnable的回答,但是尽管我实施了不同的解决方案,仍然反复出现错误。
下面是我的代码:
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();
            }
        });

    }
}

我的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

在 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

4
可以直接在onPostExecute中创建Toast,因为它已经在UI线程上执行。AsyncTask只能从UI线程执行,并且这些onSomething方法也将再次从UI线程调用。 - zapl
移除 runOnUiThread 导致了另一个问题 :( - MrYanDao
分享新问题:D。并告诉我在上传图片后你想做什么。 - Code_Life
我已经编辑了我的主要帖子。谢谢 ^^ 哦,我想在那之后我可以完成项目的其余部分,因为我将服务器响应存储在一个字符串中,稍后可以使用。我只需要先解决这个错误 :( - MrYanDao
创建一个处理程序类并将其传递到AsyncTask中,然后调用处理程序...您可以在AsyncTask中使用带有处理程序作为参数的构造函数,并从“doInBackground”中使用常量值调用处理程序以指示显示在UI线程上运行的toast - 更清晰简洁 :) - t0mm13b
如果一个AsyncTask调用另一个AsyncTask,也可能会发生这种情况。 - Stephen McCormick
3个回答

59

你试图从后台线程更新UI。请将toast移动到在UI线程上执行的onPostExecute(推荐),或者调用runOnUiThread

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

3
您有两个 Toast 调用在 doInBackground 中,这是导致异常的原因,这是正确的(但不必要的)。 - Tyler Treat
那么你的意思是我不能在doInBackground中使用Toast吗?抱歉,我有点新手不太懂 :( 对不起!编辑:我想我明白了。等一下.. - MrYanDao
2
你可以这样做,但是它们必须在runOnUiThread中才能在doInBackground中运行。 - Tyler Treat
哇!非常感谢(':)我成功解决了问题。顺便问一下,为什么在doInBackground中不能使用Toast?我的意思是,在代码运行时,为什么不能使用Toast? - MrYanDao
5
不客气!Toast是一种UI操作,而UI不能直接由后台线程进行更新,这就是为什么需要使用“runOnUiThread”。如果这个回答解决了你的问题,请将其标记为已接受的答案。 - Tyler Treat
显示剩余2条评论

8

在dev.shaunidiot.imageupload.MainActivity$uploadFile.doInBackground(MainActivity.java:128)处

您可以使用AsyncTask的进度机制,在任务运行时从doInBackground中更新UI:

替换为

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

doInBackground中使用

publishProgress(serverResponseMessage, serverResponseCode.toString());

并且在您的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();
        }
    }
}

您已经将 String 设置为 AsyncTask<Params, Progress, Result> 中的进度类型,因此如果您想将进度用于其他目的,可以尝试使用 runOnUiThread,但我不知道是否会起作用。


0

2023年,通过在异步方法内创建对象之前调用Looper.prepare()解决了这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接