Jim
Jim

Reputation: 4415

Can a post runnable get a null reference on the view it was run on?

When we are registering click listeners etc as common practice we check if the view is still there e.g.

final View someView = ...;  
someView.setOnClickListener( (l) -> {
  if(someView != null) {   
     // access view
  } 
});   

since by the time the listener is called the view could have been lost.
But in the following case:

View someView = ...;  
someView.post(() -> {
    // can someView be null here?  
});   

Upvotes: 3

Views: 618

Answers (1)

Levi Moreira
Levi Moreira

Reputation: 12005

It actually can. If you read the docs:

Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.

The post() method in the View class will simply add a runnable to the MainThread's MessageQueue. This runnable will be run at some point and if your view(Activity) gets destroyed in the meantime, the usage of someView inside that runnable can cause a memory leak (it might be null). Even if someView gets destroyed, the runnable will still hold a reference to it (a null reference) and will only release it once it executes the run method.

Upvotes: 2

Related Questions