I'm using ThreadHandler in my app this way,
public class MessageThread extends HandlerThread {
Handler mHandler;
public MessageThread() {
super("Message Thread");
}
public void queueProcessMessage(msgObject mObj) {
mHandler.obtainMessage(PROCESS_MESSAGE, mObj).sendToTarget();
}
@Override
protected void onLooperPrepared() {
Commons.logIt("OnLoopPrep");
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case PROCESS_MESSAGE:
process_message((msgObject) msg.obj);
break;
default:
break;
}
}
};
}
process_message(msgObject obj) {
//Do stuff
}
}
And I initialize it in the onCreate() like so,
public void onCreate(Bundle savedInstanceState) {
MessageThread mThread = new MessageThread();
mThread.start();
mThread.getLooper();
if (mThread != null)
mThread.queueProcessMessage(Object);// this is the line the compiler is pointing at.
}
And it's working fine, the problem is that I needed to add something else where I have to start another activity waiting for result so I had to initialize/use it as shown below as the onActivityResult gets called before onCreate when I start an activity for result, this time i'm getting an error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Message android.os.Handler.obtainMessage(int, java.lang.Object)' on a null object reference
.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
MessageThread mThread = new MessageThread();
mThread.start();
mThread.getLooper();
mThread.queueProcessMessage(new msgObject("stuff"));
}
}
}
It looks like the thread is not getting initialize, what am I missing here?
Edit 1,
After discussing the issue here, it looks like it takes a bit of time for the handler to be initialized, I did this, it's ugly but it's working, any ideas of what should I do?
public void queueProcessMessage(msgObject mObj) {
while (mHandler == null)
Log.i(TAG, "Not init yet"); //It keeps on looping here
mHandler.obtainMessage(PROCESS_MESSAGE, mObj).sendToTarget();
}