Android AsyncTask [Can't create handler inside thread that has not called Looper.prepare()]

后端 未结 2 1235
说谎
说谎 2020-12-29 03:54

I\'ve created an image upload AsyncTask based on a function. And after uploading, I get this error on onPostExecute(). I read up some StackOverflow

相关标签:
2条回答
  • 2020-12-29 04:13

    You are attempting to update the UI from a background thread. Either move the toast to onPostExecute, which executes on the UI thread (recommended), or call runOnUiThread.

    runOnUiThread(new Runnable() {
        public void run() {
            // runs on UI thread
        }
    });
    
    0 讨论(0)
  • 2020-12-29 04:14

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

    You could use the progress mechanism of AsyncTasks to update UI from inside doInBackground while the task is running:

    replace

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

    in doInBackground with

    publishProgress(serverResponseMessage, serverResponseCode.toString());
    

    and add the following to your AsyncTask implementation

    @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();
            }
        }
    }
    

    You already have set String as progress type in AsyncTask<Params, Progress, Result> so in case you want to use progress for something different you can try to use runOnUiThread but I don't know if that will work.

    0 讨论(0)
提交回复
热议问题