F. Petrulio
F. Petrulio

Reputation: 95

Handler and TextView updating Issue

I don't understand how an handler can be used to update a TextView during the flow of a program. I'm testing it on a simple code like this

public class MainActivity extends AppCompatActivity {

TextView text;  
boolean isReady;  //boolean to check a new Message
String update;    //String to send to TextView



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.textView);
    Handler handler = new MyHandler();            //defined down
    MyHandlerThread thr = new MyHandlerThread(handler);  //defined in other .class file
    thr.start();
    for(int i=0;i<100;i++){   //a simple for 
        if(i%2==0)
            thr.setMessage(i + ": Divisible for 2");
        else
            thr.setMessage(i+": Not Divisible for 2");
    }

}


private class MyHandler extends Handler { //inner class
    @Override
    public void handleMessage(Message msg) {
        Bundle bundle = msg.getData();
        if(bundle.containsKey("refresh")) {
            String value = bundle.getString("refresh");
            text.setText(value);
        }
    }
}}

and this is the thread code

public class MyHandlerThread extends Thread {
private Handler handler;
private boolean isSent;
String text;
public MyHandlerThread(Handler handler) {
    this.handler = handler;
    isSent=false;
    text="";
}
public void run() {
    try {
        while(true) {
            if(isSent){
                notifyMessage(text);
                Thread.sleep(1000);
                isSent=false;
            }
        }
    }catch(InterruptedException ex) {}
}

public void setMessage(String str){
    text=str;
    isSent=true;
}

private void notifyMessage(String str) {
    Message msg = handler.obtainMessage();
    Bundle b = new Bundle();
    b.putString("refresh", ""+str);
    msg.setData(b);
    handler.sendMessage(msg);
}}

this code just print the last expected string "99: not divible for 2"

Upvotes: 0

Views: 36

Answers (1)

rupps
rupps

Reputation: 9907

You are just calling 100 times your thread setMessage, so texts will overwrite each other before your thread loop has any chance to print them.

You should implement a queue in your setMessage, then the thread loop should pop the next element from the queue, print it (sending a message via the Handler) then sleep. If no more elements are in the queue, just loop until one becomes available.

Upvotes: 1

Related Questions