Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java thread notifier - android

I'm having a slight problem with android programming. Basically what i want to achieve is to call REST web service and display results on my (existing) Activity.

Android has certain limitations, so every View on Activity must be edited by the same thread that initially created it.

Every http call MUST be in separate thread. So, since I'm not primarily java developer (QT I did), i did what seamed most logical thing to do.

  • Created separate thread to call my web service.
  • Registered main thread to be the listener.
  • Notified main thread with result of my work.

But when i tried to use that result in my listener method to change Views my application crashed throwing this exception

  • 07-15 14:40:08.569: E/AndroidRuntime(12204): FATAL EXCEPTION: Thread-31307
  • 07-15 14:40:08.569: E/AndroidRuntime(12204): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

what i do in listener is this

@Override
public void workDone(WorkerThread thread)
{
   int a = (int)thread.getResult();
   ((ImageView)root.findViewByid(ID).setImageResource(a);
}
like image 286
Rouz Avatar asked Feb 19 '26 23:02

Rouz


1 Answers

Take a look at AsyncTask, it allows you to perform work in a background thread and then return the result to the main thread.

Another alternative is to use Activity.runOnUiThread to call back to the main thread.

like image 141
Patrik Oldsberg Avatar answered Feb 22 '26 12:02

Patrik Oldsberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!