简体   繁体   中英

Android AsyncTask: Error occured while executing doInBackground()

I want to put my function in AsyncTask, but It cause error when I do it. Here is my code:

@Override
public void onClick(final View v) {
    // TODO Auto-generated method stub
    switch (v.getId())
    {
        case R.id.btnCreateVideo:
        {
            MP4VideoParams mParams = new MP4VideoParams(v.getContext(), "mnt/sdcard/out.mp4", "MOBILE");
            new MyMP4VideoCreator().execute(mParams);
        }
        break;
        default:
        {
            Toast.makeText(this, "Nothing", Toast.LENGTH_SHORT).show();
        }
    }
}

An my AsyncTask is simple:

private class MyMP4VideoCreator extends AsyncTask<MP4VideoParams, Void, Void> {

    @Override
    protected Void doInBackground(MP4VideoParams... MP4Video) {
        // TODO Auto-generated method stub

        try {
            CreateMP4Video.CreateVideo(MP4Video[0].getContext(), MP4Video[0].getOutput(), MP4Video[0].getQuality());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

The LogCat:

java.lang.RuntimeException: An error occured while executing doInBackground()
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

This is my first time using AsyncTask, please help me. Thank you in advance.

Basically the exception Can't create handler inside thread that has not called Looper.prepare() throws while you try to access UI directly from a worker thread.

The method CreateMP4Video.CreateVideo , is it your own implementation or any 3rd party library? Make sure you are not trying to directly access UI in that function (Such as Toast). Use a handler for creating Toasts while inside worker thread.

You are trying to access Main thread from background thread .

In Asynctask doinbackground() method runs on background thread where as postexecute() runs on Main thread .

So try to capture video in onPostexecute or you can ovveride runonUithread() in doinbackground()

I create a Context variable, two String variables (output, quality) and pass those variables when I new a class MyMP4VideoCreator.

I also check those functions when I create a MP4Video and remove all functions belong to Toast.

Luckily for me, it worked. Big thanks to everyone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM