0

This function resides in a Service when called by an activity it should will generate a random number and add that to a ArrayList. Everytime a new item is added it will try to update UI via update which calls runOnUiThread to use these number to plot a line graph and then wait 1 second. I want the update to happen every second. Is there a way to force activity to clear execute its message queue? As of right now it waits until this thread finish executing before it updates. Should I implement this in AsyncTask instead?

public void pollDP(int numPt){
    final Random gen = new Random();
    final int numPtF = numPt;
    serverLoadList = new ArrayList<Integer>();

        new Thread(new Runnable(){
            @Override
            public void run(){
                for(int i = 0; i < numPtF; i++){
                    serverLoadList.add(gen.nextInt());
                    update();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }

        }).run();
    }
}
CatFish
  • 57
  • 1
  • 5
  • 1
    try using Thread.start() instead of Thread.run(). If you use run(), the Runnable is not launched in a new Thread. If this didn't help, post some code of the update() method. Am i right by guessing you are calling pollDP from UI-Thread? – Martze Jun 29 '12 at 08:37
  • it's called from a Thread in Activity so no? I am still new to android. – CatFish Jun 29 '12 at 09:04
  • When I use start() it's causing null pointer somewhere in the graphView library. I am quite confused as to why. – CatFish Jun 29 '12 at 09:11
  • Ah okay, now i think i get how your app is built. I think you should implement a Handler (like Rinkalkumar said) in your Activity that shows the graph and receive and handle messages with the new value you generate in a thread in your service. This way you are not updating your Activity's UI from a service directly, which causes problems. – Martze Jun 29 '12 at 09:23
  • Well I figured out why it dies when I use .start() it's because I have an off by one error when making an array. I fixed that and it's updating properly with runOnUiThread(). Thank you! – CatFish Jun 29 '12 at 10:11

2 Answers2

0

Try using MessageHandler to fulfill your requirements visit this link for more details, do necessary changes according to your need :)

RPB
  • 16,006
  • 16
  • 55
  • 79
0

The solution is in the comment on my question by Martze. I am making this the solution for my problem.

try using Thread.start() instead of Thread.run(). If you use run(), the Runnable is not launched in a new Thread. If this didn't help, post some code of the update() method. Am i right by guessing you are calling pollDP from UI-Thread? – Martze

CatFish
  • 57
  • 1
  • 5