KaliMa
KaliMa

Reputation: 2060

Error using Thread.sleep in an Asynctask

I am trying to add some sleep-time in my Asynctask because right now my ProgressDialog is too fast when there isn't much data to load.

I tried this:

@Override
protected Boolean doInBackground(Void... params) {
    try {
        progressDialog.setMessage("Loading first thing...");
        firstThing();
        progressDialog.incrementProgressBy(1);
        Thread.sleep(500);
        //...repeat above four lines a few times for second, third, fourth thing, etc
        return true;
    }
    catch (Exception e) {
        Log.e("MyClassName", "There was an error: " + e);
        return false;
    }
}

I am getting the error "Only the original thread that created a view can touch its views."

Upvotes: 0

Views: 686

Answers (1)

kris larson
kris larson

Reputation: 31015

You'll have to override onProgressUpdate() as well as doInBackground().

            // do this before asynctask.execute();
            progressDialog.setMessage("Loading first thing...");


@Override
protected Boolean doInBackground(Void... params) {
    try {
        firstThing();
        Thread.sleep(500);
        // this method invokes onProgressUpdate on the UI thread
        publishProgress();
        return true;
    }
    catch (Exception e) {
        Log.e("MyClassName", "There was an error: " + e);
        return false;
    }
}

@Override
protected void onProgressUpdate(Void... params) {
    progressDialog.incrementProgressBy(1);
}

Upvotes: 2

Related Questions