StackOverflowed
StackOverflowed

Reputation: 5975

static runnable in Activity

I am modifying the following code in my activity:

new Handler().postDelayed(new Runnable() {
 public void run() {
    txtStatus.setText("hello");
  }
}, 1000);

to:

static Runnable myRunnable = new Runnable() {
public void run() {
   txtStatus.setText("hello");
};

new Handler().postDelayed(myRunnable, 1000);

Which obviously doesn't work, since we're referencing a non static variable.

This doesn't work either:

public void setText() {
  txtStatus.setText("hello");
}
static Runnable myRunnable = new Runnable() {
public void run() {
   setText(); // doesn't work
   MyActivity.this.setText(); // still doesn't work

};

new Handler().postDelayed(myRunnable, 1000);

so how would my initial example be rewritten to use a static class instead of an anonymous inner class (to avoid the potential of a memory leak)?

Upvotes: 2

Views: 5056

Answers (2)

Desert
Desert

Reputation: 2303

You can use WeakReference to avoid memory leak problems. Here is some code, which illustrate this idea

public static class MyRunnable implements Runnable {

    private WeakReference<Activity> activityRef;

    public MyRunnable(Activity activity) {
        activityRef = new WeakReference<Activity>(activity);
    }

    public void run() {
         //some code
    }
}

private MyRunnable runnable = new MyRunnable(this);

Upvotes: 5

MaciejG&#243;rski
MaciejG&#243;rski

Reputation: 22232

Try something like this:

private Runnable myRunnable = new Runnable() {
    public void run() {
        txtStatus.setText("hello");
    }
};

// somewhere in code
txtStatus.postDelayed(myRunnable, 1000);

// in onPause or onDestroy
txtStatus.removeCallbacks(myRunnable);

Notes:

  • this avoids memory leaks, as your run will never be called after onDestroy if you call removeCallbacks
  • I replaced new Handler() with txtStatus, because every View has its own instance of Handler and there is no need to create additional one

Upvotes: 5

Related Questions