Adam
Adam

Reputation: 9049

I'm receiving illegalstatexception when executing method from Timer

When I run my method from the constructor of the mainscreen it works, but if invoked in the timer then I get the error.

Here is my method:

public void buildDesc(){


    try {


        JSONObject event = array.getJSONObject(currentPage);
        String title = event.getString("title");

        String by = event.getString("by");
        String by_name = event.getString("by_name");
        String summary = event.getString("summary");
        int nid = event.getInt("nid");


    vfm.add(new LabelField(title));
        System.out.println("The Title:"+title);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

And the timer:

timer = new Timer();//Create the timer to loop the events every 5 seconds
        timer.scheduleAtFixedRate(new TimerTask(){
            public void run() {
                currentPage++;
                if(currentPage > 3){
                    currentPage = 0;    
                }
                System.out.println("Page Position:"+pagePosition(currentPage+1));
                gallery.setHorizontalScroll(pagePosition(currentPage));

                buildDesc();

            }
        }, 0, 10000);

I read a Android question that says, perhaps, I can't make changes to the UI if not on the UIThread?

Upvotes: 0

Views: 50

Answers (1)

binarycreations
binarycreations

Reputation: 3181

I think your hunch is right, in BlackBerry you shouldn't do any work on the Ui thread. I guess the Timer thread is getting terminated for it's behaviour which is why you are getting an IllegalStateException. A quick guide to the UI thread can be found here.

Try :

timer = new Timer();//Create the timer to loop the events every 5 seconds
timer.scheduleAtFixedRate(new TimerTask(){
    public void run() {
        currentPage++;
        if(currentPage > 3){
            currentPage = 0;    
        }
        System.out.println("Page Position:"+pagePosition(currentPage+1));

        synchronized(UiApplication.getUiApplication().getEventLock())) {  
            // UI Code here
            gallery.setHorizontalScroll(pagePosition(currentPage));

        buildDesc();
        } 
    }
}, 0, 10000);

Note: The above is untested.

Upvotes: 1

Related Questions