I was just trying to figure out if I could get a NULL pointer exception with the following code. The cause could be this: The check is done at time X. But, I post the runnable to the handler, he will execute at X+5. He should have a strong reference, therefore preventing the Runnable being gc-ed in between.
Am I correct? (that what I call easy reputation, a YES is enough. A no, you have to explain 🙂
public class WeakRunnableUiList
{
private ArrayList<WeakReference<Runnable>> _items = new ArrayList<WeakReference<Runnable>>();
private Handler _handler = new Handler(Looper.getMainLooper());
public void Add(Runnable r)
{
_items.add(new WeakReference<Runnable>(r));
}
public void Execute()
{
ArrayList<WeakReference<Runnable>> remove = new ArrayList<WeakReference<Runnable>>();
for (WeakReference<Runnable> item : _items)
{
if (item.get() == null)
{
remove.add(item);
}
else
{
_handler.post(item.get());
}
}
_items.removeAll(remove);
}
}
No.
Put this into your code just before
_handler.post(...:And then in the main program:
Will give you
12-03 21:56:01.521: E/Item is NULL now!(1071): Item is NULL now!So the runnable can get NULL after your first check!
Do it like this:
But you can post nulls to handlers:
_handler.post(null);, and it will not throw a nullpointer actually.