2

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.

Luong Truong
  • 1,953
  • 2
  • 27
  • 46

3 Answers3

2

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.

gnuanu
  • 2,252
  • 3
  • 29
  • 42
  • The method CreateMP4Video.CreateVideo is my own implementation, but I also use some 3rd party library too. I do not know if I am trying to directly access UI or not. Do you have any document about it? Thank you – Luong Truong Jul 10 '14 at 03:24
  • Check this [Blog](http://prasanta-paul.blogspot.kr/2013/09/android-looper-and-toast-from.html) – gnuanu Jul 10 '14 at 03:50
1

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()

someone
  • 427
  • 2
  • 11
0

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.

Luong Truong
  • 1,953
  • 2
  • 27
  • 46