2

Could someone explain to me how to use switch with the what field to determine what code to execute. Also how to create message obj to use in the switch would be great too.

Example of my handler code:

Handler uiHandler = new Handler(){
    public void handleMessage(Message msg){
        switch(msg.what){

        }
    }
};
Dakota Miller
  • 493
  • 1
  • 4
  • 22

2 Answers2

4

If you are using handlers, I assume that you want to do some work in a different thread and are using handler to communicate b/w the thread that you are starting and the main thread. Take the following example:

private static final int SUCCESS = 0;
private static final int FAIL = 1;

//This is the handler
Handler uiHandler = new Handler(){
    @Override
    public void handleMessage(Message msg){
        //Here is how you use switch statement
        switch(msg.what){
        case SUCCESS:
            //Do something      
            break;
        case FAIL:
            //Do something
            break;
        }

    }
};

//Here is an example how you might call it
Thread t = new Thread() {
    @Override
    public void run(){
        doSomeWork();
        if(succeed){
            /*we can't update the UI from here so we'll signal our handler 
             and it will do it for us.*/
            // 'sendEmptyMessage(what)' sends a Message containing only the 'what' value.
            uiHandler.sendEmptyMessage(SUCCESS);
        }else{
            uiHandler.sendEmptyMessage(FAIL);
        }
    }   
}

Credit goes to these two threads: They might be a good read: Android: When should I use a Handler() and when should I use a Thread? & Android Handler actions not being processed

Hope this helps.

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
  • Very helpfully I think I can also send a bundle of data with that right? – Dakota Miller Jun 23 '13 at 04:42
  • 1
    a bundle is a last resort, firt use arg0, arg1 and obj. use Handler.obtainMessage() or Message.obtain() to initialize a Message with proper arguments. also its not true that Handler is used to talk to the different Thread what OP said, you can also use it to talk to yourself – pskink Jun 23 '13 at 04:58
0
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {             
        case SECOND_VALUE:
            String s = (String) msg.obj;  // if msg.obj is a string
            break;

        case FIRST_VALUE:
            AnotherObject = (AnotherObject) msg.obj;   // if it is another object
            break;

        default:
            super.handleMessage(msg);
        }
    }
stinepike
  • 54,068
  • 14
  • 92
  • 112