BeefEX BeefEX - 3 months ago 10
Android Question

Android ASyncTask Crashing on Android 4 and below

I am using

ASyncTask
to do simple animation in my app. But it only works on Android 5.0+, below that it just crashes and says that I edit UI from the wrong thread. Here is my code:

private class AlphaCorrect extends AsyncTask<Integer, Integer, Integer> {
float alpha;
@Override
protected Integer doInBackground(Integer[] params) {
Log.i("back","running");
for (float i = 0.0f; i < 0.9; i += 0.02) {
alpha = i;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Update();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (float i = 0.8f; i > -0.1f; i -= 0.02) {
alpha = i;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Update();
}
return null;
}

@Override
protected void onPreExecute() {
Log.i("run", "RUN");
canClick = false;
}

@Override
protected void onPostExecute(Integer result) {
canClick = true;
}

protected void Update() {
correct.setAlpha(alpha);
}
}


I tried
Runnable
,
Thread
and some other things already. Any ideas?

Answer

You do exactly what the error says - you update UI from another thread. Override onProgressUpdate method of AsyncTask, put Update() inside it and call publishProgress(0) in your doInBackground method