title: HandlerThread null exception - Android
body: <p>I'm using ThreadHandler in my app this way, </p>
  
  <pre><code>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
     }
  
  }
  </code></pre>
  
  <p>And I initialize it in the onCreate() like so, </p>
  
  <pre><code>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.
  }
  </code></pre>
  
  <p>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 </p>
  
  <pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Message android.os.Handler.obtainMessage(int, java.lang.Object)' on a null object reference
  </code></pre>
  
  <p>.</p>
  
  <pre><code>@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"));
          }  
  
      }
    }
  </code></pre>
  
  <p>It looks like the thread is not getting initialize, what am I missing here? </p>
  
  <p>Edit 1, </p>
  
  <p>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?</p>
  
  <pre><code>    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();
  
      }
  </code></pre>