Cemre Mengü
Cemre Mengü

Reputation: 18774

Setting a label in a thread causes IllegalStateException

I have a thread like:

    startButton.setChangeListener(new FieldChangeListener() {
        public void fieldChanged(Field arg0, int arg1) {

                    Thread thread = new Thread(){
                        public void run() {
                            uploadFile();
                        }
                    };
                    thread.start();
                }
            //});

    });

The uploadFile method contains the line label_up_result.setText(result); which causes an IllegalStateException.

label_up_result is defined like: final LabelField label_up_result=new LabelField("", LabelField.FIELD_LEFT);

What can be the problem ? How can I fix it ?

Upvotes: 1

Views: 164

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234857

The problem is probably that you are trying to update the UI from a worker thread. There are two approaches. You can synchronize on the event lock:

synchronized(UiApplication.getUiApplication().getEventLock())) {
    label_up_result.setText(result);
}

or you can create a Runnable to execute on the UI thread:

UiApplication.getUiApplication().invokeLater(new Runnable() {
    public void run() {
        label_up_result.setText(result);
    }
});

Upvotes: 4

Rudolf Mühlbauer
Rudolf Mühlbauer

Reputation: 2531

I don't know about blackberry, but usually you need to perform the ui-actions in the ui-thread. SwingUtilities.invokeLater provides that functionality in JavaSE, http://www.java2s.com/Code/Java/Swing-JFC/Swinginvokelater.htm

Upvotes: -2

Related Questions