1

I want to run a classic flood fill algorithm that has a visual representation of how the algorithm progresses; i.e a series of buttons that turn black to show the sequence of the algorithm. I don't want to cheat by producing an iterative version of the recursive algorithm. P oorly tabbed pseudocode ahead:

public void floodFill(int x, int y, String targetColor,String replacementColor) {
            if *out of bounds* return
              else
               if button = target then return
                else
                 Switchbuttontoblack(button);
                 PAUSE;
         floodFill(x - 1, y, targetColor, replacementColor);
         floodFill(x + 1, y, targetColor, replacementColor);
         floodFill(x, y - 1, targetColor, replacementColor);
         floodFill(x, y + 1, targetColor, replacementColor);
}

But, although the algorithm executes there buttons only change colour all at once at the end of the algorithm.

This might be due to be a non UI thread as in Android timer updating a textview (UI).

Therefore I implemented a runnable at the PAUSE line of the algoithm (i.e
handler.post(runnable);

where runnable is

private Runnable runnable = new Runnable() {
       public void run() {

            Log.d("RUNableworking","RUNableworking");
            handler.postDelayed(this, 1000);

       }
    };

Running from the Floodfill thread = nothing. Running from onCreate I see the log just fine.

I'm not too keen on polling the runnable; there must be a better way of doing this?

Community
  • 1
  • 1
stevenpcurtis
  • 1,907
  • 3
  • 21
  • 47

1 Answers1

1

There's a command in Activity called runOnUiThread(), which comes in quite handy. The only problem is that the UI running is queued. You also might be able to use Handler objects to send the UI update calls to the UI thread.

However, if you are going step-by-step, do you really need to use another thread?

Update: are you doing the flood fill in the onDraw()? If so, it won't go step-by-step

Joe Plante
  • 6,308
  • 2
  • 30
  • 23
  • TBH, threads are complicating matters. But just using the vanilla function (as above) does not seem to update the UI until the end of the execution; although it does not explicitly create a new thread I assume it does to create the problem? – stevenpcurtis Nov 05 '12 at 14:04
  • Nope, not using onDraw(); just set the background colour switchbutt.setBackgroundColor(Color.BLACK); – stevenpcurtis Nov 05 '12 at 14:29
  • Oh! I misread. I thought you were using pixel plotting, not buttons. Sometimes you have to invalidate the buttons to get them to update. I bet Android is queuing up the BG change requests and doing them in a single pass, instead of one-by-one. You definitely want to do some sort of timer mechanism for each pass in order for this, or an iteration flipper button – Joe Plante Nov 08 '12 at 17:03