I\'ve created an image upload AsyncTask
based on a function. And after uploading, I get this error on onPostExecute()
. I read up some StackOverflow
You are attempting to update the UI from a background thread. Either move the toast to onPostExecute
, which executes on the UI thread (recommended), or call runOnUiThread
.
runOnUiThread(new Runnable() {
public void run() {
// runs on UI thread
}
});
at dev.shaunidiot.imageupload.MainActivity$uploadFile.doInBackground(MainActivity.java:128)
You could use the progress mechanism of AsyncTask
s to update UI from inside doInBackground
while the task is running:
replace
Toast.makeText(getApplicationContext(), serverResponseMessage,
Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
serverResponseCode.toString(), Toast.LENGTH_SHORT)
.show();
in doInBackground
with
publishProgress(serverResponseMessage, serverResponseCode.toString());
and add the following to your AsyncTask
implementation
@Override
protected void onProgressUpdate(String... values) {
if (values != null) {
for (String value : values) {
// shows a toast for every value we get
Toast.makeText(MainActivity.this, value, Toast.LENGTH_SHORT).show();
}
}
}
You already have set String
as progress type in AsyncTask<Params, Progress, Result>
so in case you want to use progress for something different you can try to use runOnUiThread
but I don't know if that will work.