0

I am trying to pass my Main activity into a java class that has a running thread. When the thread is called I then have to reference some objects back in my activity class that do some work and update the UI. My code looks like this.

/**
 *
 */
public class MainActivity extends Activity {

     Person person;

     @Override
     public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);

          person = new Person();
     }


     public void updateInfo(String action) {

          person.setAction(action);

          //redraw the person to the gui
          ImageView image = (ImageView) findViewById(R.id.action);
          int id = getResources().getIdentifier(person.getCurrentAction(),"drawable", getPackageName());
          image.setImageResource(id);


     }
 }

 /**
  *
  */
 public class ThreadClass {

     private MainActivity mainActivity;

     public SocketClient(MainActivity mainActivity) {
           this.mainActivity = mainActivity;
           new MyThread().start();
     }

     private class MyThread extends Thread {

          public void run() {
              try {
                  while(!isInterrupted() {
                      mainActivity.updateInfo("Person is running");
                  }
              }
          }

     }


 }

When I do it this way I get the error that I am not updating the view in the correct thread. android.View.ViewRoot$CalledFromWrongThreadException. What am I doing wrong here? Also this code most likely will not compile its pseudo code because I had to take out all of the other logic.

medium
  • 4,136
  • 16
  • 55
  • 66
  • You should be using [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html) or a [Handler](http://developer.android.com/reference/android/os/Handler.html) See [this article for some great examples](http://www.vogella.com/articles/AndroidPerformance/article.html) – FoamyGuy Jul 23 '12 at 13:52

1 Answers1

1

If I understand the problem, I advise you to work from a different angle.

You should never pass your activity class. The activity class is the controller, the master of what happens.

So you pass objects and data to your background thread. When the Main UI is called, the UI will ask back these object from the thread and update his UI.

If you want this to happen on a regular base, you should look to implement a listener in your thread, that way the main thread can get notified when to update it's data.

a final way is to use the good old observer pattern, but I'm not to keen on using that one.

EDIT: Take a look at AsyncTask: AsyncTask Android example

Community
  • 1
  • 1
Yoeri
  • 2,249
  • 18
  • 33