Toni Joe
Toni Joe

Reputation: 8417

Android progress indicator increments at once in a for loop

I want to increment a progress indicator while scanning all the files in my device. here is a simplified implementation:

val totalFiles = 10000
progressBar.max = totalFiles
repeat(totalFiles) {
    Thread.sleep(5) // to slow the loop for debugging purposes
    binding.circularProgress.incrementProgressBy(1)
}

The progress bar is supposed to increment by 1 every 5 ms, but instead, it increments at once after the loop has finished. I don't understand why this isn't working. Any idea guys? Thanks

Upvotes: 0

Views: 226

Answers (1)

laalto
laalto

Reputation: 152867

Thread.sleep() blocks the main UI thread and the progressbar does not get a chance to update itself.

Rather than blocking the main thread, use some concurrency mechanism (rxjava, coroutines, asynctask, raw threads) to do your processing, posting UI updates to the main thread.

Upvotes: 1

Related Questions