11

This problem drives me crazy. I miss some basic but very important knowledge about how to handle long operations in a new thread created within an activity and how to modify view components like text and such after the long operation's done.

Let me first show you the part of my code where this problem happens:

mProgressDialog = ProgressDialog.show(mContext, "Tripplanner", "please wait...", true, false);
connectAndGetRoute();


private void connectAndGetRoute(){

    new Thread(){
        @Override
        public void run() {
            try {
            if(!connectTo9292ov()) return;// conncetto9292ov() connects to a website, parses the reasult into an arraylist. The arraylist contains route.

            } catch(UnknownHostException e){
                Toast.makeText(mContext, "failed to connect to server", Toast.LENGTH_LONG).show();
            }catch (ClientProtocolException e) {
               Toast.makeText(mContext, "failed to connect to server", Toast.LENGTH_LONG).show();                   
        } catch (IOException e) {
                Toast.makeText(mContext, "failed to connect to server", Toast.LENGTH_LONG).show();
            }

            handler.post(runConnection);
        }

    }.start();

    handler = new Handler();
    runConnection = new Runnable(){
        @Override
        public void run() {
            mProgressDialog.dismiss();
            showOnScreen();
        }   
    };
}

and this is the error I get:

ERROR/WindowManager(8297): Activity mp.tripplanner.OvPlanner has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@46368a28 that was originally added here
ERROR/WindowManager(8297): android.view.WindowLeaked: Activity mp.tripplanner.OvPlanner has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@46368a28 that was originally added here
ERROR/WindowManager(8297): at android.view.ViewRoot.<init>(ViewRoot.java:251)
ERROR/WindowManager(8297): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
ERROR/WindowManager(8297): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
ERROR/WindowManager(8297): at android.view.Window$LocalWindowManager.addView(Window.java:424)
ERROR/WindowManager(8297): at android.app.Dialog.show(Dialog.java:241)
ERROR/WindowManager(8297): at android.app.ProgressDialog.show(ProgressDialog.java:107)
ERROR/WindowManager(8297): at android.app.ProgressDialog.show(ProgressDialog.java:95)
ERROR/WindowManager(8297): at mp.tripplanner.OvPlanner$3.onClick(OvPlanner.java:351)
ERROR/WindowManager(8297): at android.view.View.performClick(View.java:2408)
ERROR/WindowManager(8297): at android.view.View$PerformClick.run(View.java:8817)
ERROR/WindowManager(8297): at android.os.Handler.handleCallback(Handler.java:587)
ERROR/WindowManager(8297): at android.os.Handler.dispatchMessage(Handler.java:92)
ERROR/WindowManager(8297): at android.os.Looper.loop(Looper.java:144)
ERROR/WindowManager(8297): at android.app.ActivityThread.main(ActivityThread.java:4937)
ERROR/WindowManager(8297): at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/WindowManager(8297): at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/WindowManager(8297): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
ERROR/WindowManager(8297): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
ERROR/WindowManager(8297): at dalvik.system.NativeStart.main(Native Method)

But another error message is written to the log before the above one, which is:

ERROR/AndroidRuntime(8297): FATAL EXCEPTION: Thread-9
ERROR/AndroidRuntime(8297): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
ERROR/AndroidRuntime(8297): at android.os.Handler.<init>(Handler.java:121)
ERROR/AndroidRuntime(8297): at android.widget.Toast.<init>(Toast.java:68)
ERROR/AndroidRuntime(8297): at android.widget.Toast.makeText(Toast.java:231)
ERROR/AndroidRuntime(8297): at mp.tripplanner.OvPlanner$4.run(OvPlanner.java:371)

Thank you for your help.

skaffman
  • 398,947
  • 96
  • 818
  • 769
mnish
  • 3,877
  • 12
  • 36
  • 54

3 Answers3

4

Your Handler needs to be created in your UI thread for it to be able to update the UI. I would then use the sendMessage method of the handler, rather than posting a runnable:

private static final int HANDLER_MESSAGE_ERROR = 0;
private static final int HANDLER_MESSAGE_COMPLETED = 1;
...
private void connectAndGetRoute(){
    new Thread(){
        @Override
        public void run() {
            try {
                if(!connectTo9292ov()) return;

            } catch(UnknownHostException e){
                sendMessage(HANDLER_MESSAGE_ERROR);
            } catch (ClientProtocolException e) {
                sendMessage(HANDLER_MESSAGE_ERROR);
            } catch (IOException e) {
                sendMessage(HANDLER_MESSAGE_ERROR);
            } finally {
                sendMessage(HANDLER_MESSAGE_COMPLETED);
            }
        }
        private void sendMessage(int what){
            Message msg = Message.obtain();
            msg.what = what;
            mHandler.sendMessage(msg);
        }
    }.start();

}
...
private Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what){
        case HANDLER_MESSAGE_ERROR:
            Toast.makeText(mContext, "failed to connect to server", Toast.LENGTH_LONG).show();
            break;
        case HANDLER_MESSAGE_COMPLETED:
            mProgressDialog.dismiss();
            showOnScreen();
            break;
        default:
            Log.w("MyTag","Warning: message type \""+msg.what+"\" not supported");
        }
    }
}
dave.c
  • 10,910
  • 5
  • 39
  • 62
  • 1
    Thaks alot, this solved the problem. I just wanted to know you do you recommend using the sendMessage of the Handler rather than posting a runnable? – mnish Mar 03 '11 at 16:14
  • 1
    @mnish well both methods should work, I just find it's easier to keep track of your UI updates if they are all in one place. The separation of responsibility is easier to see using `sendMessage`, so I find it easier to debug. – dave.c Mar 03 '11 at 17:56
1

Just a quick idea.

i think, it's your toast-messages within thread. Try to comment them out.

If you still want to show messages, save the status of your thread and handle it in your handler. Call for that your handler from finally block

mProgressDialog = ProgressDialog.show(mContext, "Tripplanner", "please wait...", true, false);
connectAndGetRoute();


private void connectAndGetRoute(){

    new Thread(){
        @Override
        public void run() {
            try {
            if(!connectTo9292ov()) return;// conncetto9292ov() connects to a website, parses the reasult into an arraylist. The arraylist contains route.

            } catch(UnknownHostException e){
                // an int member of your activity
                threadStatus = 404;
                // Toast.makeText(mContext, "failed to connect to server", Toast.LENGTH_LONG).show();
            }catch (ClientProtocolException e) {
                threadStatus = 404;
               // Toast.makeText(mContext, "failed to connect to server", Toast.LENGTH_LONG).show();                   
        } catch (IOException e) {
                threadStatus = 404;
                // Toast.makeText(mContext, "failed to connect to server", Toast.LENGTH_LONG).show();
            }
            finally {
            handler.post(runConnection);}
        }

    }.start();

    handler = new Handler();
    runConnection = new Runnable(){
        @Override
        public void run() {
            if (threadStatus == 404) { Toast.makeText(mContext, "failed to connect to server", Toast.LENGTH_LONG).show();}
            else {
            mProgressDialog.dismiss();
            showOnScreen();}
        }   
    };
}
Tima
  • 12,765
  • 23
  • 82
  • 125
  • You guessed right, and guessed it too but wasn't sure, and still don't know how to solveit. Because I don't understand the solution you offered :D. could you please tell me what you mean by saving the status of the thread and how do I do that? I actually need more explanation on your solution :D. Sorry. – mnish Mar 03 '11 at 14:48
  • 1
    i modificated your code a bit. If you ask me for reason, then you are not allowed to update your ui from thread. You should do it outside. – Tima Mar 03 '11 at 14:57
  • and take a look of the @Olsavage's answer – Tima Mar 03 '11 at 14:59
1

Sample code:

new Thread(new Runnable() {                 
                @Override
                public void run() {
                    doNotUIthings();
                    updateUI.sendEmptyMessage(0);   //Update ui in UI thread
                }
                private Handler updateUI = new Handler(){
                    @Override
                    public void dispatchMessage(Message msg) {
                        super.dispatchMessage(msg);
                        updateUI();
                    }
                };
            }).start();

But I recommend to use AsyncTask instead of Java Threads.

Olsavage
  • 1,118
  • 8
  • 11
  • thanks alot. Never though of this actually. Although I dont know how this works but I will definately consider using it in the future of if the current problem occurs again. But for now I will go on with the solution offered by Dave.c because it works just fine for me. – mnish Mar 03 '11 at 16:19