im getting sometimes null pointer exception while accessing handler created in thread.
I`m using two approaches.
One is service with thread, in which i create handler and access it by service method.
Second is Thread created in activity, in which i`m making Thread, starting it, and making handler.
Problem is quite simple, handler is created asynchronously to main thread. And i’am accessing it in main (gui thread), so sometimes it will create, and sometimes it will be null at time of getting it.
i could make on gui thread while(handler == null){
}
but it’s really bad solution. I`m looking for some elegant way to do this.
Everything is in main thread.
Thread t = new Thread(new Runnable {
Looper.prepare();
handler = new Handler();
Looper.Loop();
}
handler.post(new Runnable{}) //at this point sometimes handler is still null.
and it is created like few ms later. But still at this point i need valid handler
to background thread
Unless “hander” attribute is volatile, using a while-loop or sleeping is not only unelegant, but also wrong – even if you find that handler is not null, you are not allowed to use it. Since there is no happens-before relation between writing to handler and creating hander instance, the main thread might see the reference to handler BEFORE ITS CONSTRUCTOR IS RUN;
A safe choice to hand off a simple reference is SynchronousQueue (it’s not really a queue, it has no internal capacity, it’s only there to move an object between threads). You would use it like so (off my head, some typos highly possible):