Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, Handler messaging

I have some very simple code to do with handlers:

 Handler seconds=new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
      bar.incrementProgressBy(5); 
      tView1.setText("r:"+msg);
    } 
  }; 

And my thread:

Thread seconds_thread=new Thread(new Runnable() { 
              public void run() { 
                try { 
                  for (int i=0;i<20 && isRunning.get();i++) { 
                    Thread.sleep(1000); 

                    Message m = new Message();
                    Bundle b = new Bundle();
                    b.putInt("what", 5); // for example
                    m.setData(b);
                    seconds.sendMessage(m);



                  } 
                } 
                catch (Throwable t) { 
                  // just end the background thread 
                } 
              } 
            }); 

As you can see above i am trying to change the value of "what" in the message, so i can do different things based on the message, but according to "tView1.setText("r:"+msg)" the value of "what" is not changing to 5 :(
it is only showing "what=0"

How do I change the values of Message so that I can do different things based on the message?

Thanks!

like image 949
Ryan Avatar asked Jul 24 '11 03:07

Ryan


2 Answers

You must get the data from the Message (as Bundle then as int) you have sent in the handler you do:

Handler seconds=new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
      int sentInt = msg.getData().getInt("what");
      bar.incrementProgressBy(5); 
       tView1.setText("r:"+Integer.toString(sentInt));
    } 
  }; 
like image 193
Nikola Despotoski Avatar answered Sep 17 '22 16:09

Nikola Despotoski


You need to extract the message in the same way you got it:

public void handleMessage(Message msg) { 
  bar.incrementProgressBy(5); 
  Bundle data = msg.getData();
  tView1.setText("r:"+data.getInt("what"));
} 

Sorry for not clarifying that in the previous answer...

P.S. I ignored checking for null for simplicity, but you should check if data is null...

like image 41
MByD Avatar answered Sep 21 '22 16:09

MByD