Skip to content Skip to sidebar Skip to footer

Cannot Touch View From Another Thread, How To Make It Possible?

I cant figure out why i cant set text to my textView tv. getting: E/AndroidRuntime(686): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created

Solution 1:

It seems like you put your entire Activity here, and that it also includes a service, and you didn't try to narrow down your problem.

in your route_calc thread you call showToast, this is probably one of your problems, you should call showToast (or any other UI function) from your Handler.

Something like this:

Do anything you want on your thread:

   new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        someHeavyStuffHere(); //Big calculations or file download here.
                        handler.sendEmptyMessage(SUCCESS);
                    }
                    catch (Exception e)
                    {
                        handler.sendEmptyMessage(FAILURE);
                    }
                }
            }).start();

When your data is ready, tell the handler to put it in a view and show it:

protected Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what == SUCCESS)
            {
                setCalculatedDataToaView(); // the data you calculated from your thread can now be shown in one of your views.
            }
            else if (msg.what == FAILURE)
            {
                errorHandlerHere();//could be your toasts or any other error handling...
            }
        }
    };

Post a Comment for "Cannot Touch View From Another Thread, How To Make It Possible?"