Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get handler return null in LooperThread

public class LooperThread extends Thread {

private Handler handler = null;

public Handler getHandler() {
    return handler;
}

@Override
public void run() {
    Looper.prepare();
    handler = new Handler();
    Looper.loop();
}

}

class Helper {
    private static LooperThread databaseThread = null;

static {
    databaseThread = new LooperThread();
    databaseThread.start();
}

public void postRunable(Runnable r) {
    databaseThread.getHandler().post(r);
    databaseThread.getHandler().sendMessage(new Message());
}
}

//ui thread.

 class UIActivity extends Activity {

     private Helper helper = new Helper();

     public void onCreate(Bundle savedInstanceState) {
         helper.postRunnable(new Runnable() {
              public void run() {
                  //work asyn,like query from db.
              }
         });
     }
 }

sometimes call databaseThread.getHandler().post(r); ,it return null,sometime are not,why this?as usual,handler should be initial by static block.

like image 565
venciallee Avatar asked Oct 20 '22 12:10

venciallee


1 Answers

You are some times getting a null Handler because calling databaseThread.start(); in the the static initializer only ensures that the thread will be started at some point in the future this means thats creating a race condition between the handler getting created inside the new thread and getHandler() being called in the old one. Having a thread with a background looper is a very common pattern in Android so there is a class to help us with this.

First get rid of your LooperThread class and use the SDK's HandlerThread instead.

Your Helper class should now look like

class Helper {
    private static final HandlerThread databaseThread;
    private static final Handler dbHandler;
    static {
        databaseThread = new HandlerThread("database thread");
        databaseThread.start();
        // If you have called HandelerThread#start()
        // HandlerThread#getLooper() will block until the looper is initialized and Looping
        dbHandler = new Handler(databaseThread.getLooper());
    }

    public void postRunable(Runnable r) {
        dbHandler.post(r);
    }
}
like image 57
gabcas Avatar answered Oct 23 '22 09:10

gabcas