Nathiel Paulino Nathiel Paulino - 24 days ago 9
Android Question

How to create a progress dialog inside of AsyncTask?

I have a FullRest API which returns a StatusCode, and I succeed, the problem is, the progress dialog cannot be called from AsyncTask, I just want to "show" the user what's happened,

if(statusCode == 201)
.. Successful POST, so far :

PostBaseClass..

public class PostBase {

private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private String Url="http://192.168.0.101:3000/";

OkHttpClient client = new OkHttpClient();

int POST(final PostModel model) throws IOException{
Gson gson = new Gson();
String modelJson = gson.toJson(model);

RequestBody body = RequestBody.create(JSON,modelJson);
Request request = new Request.Builder()
.url(Url + "api/gone/POST")
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.code();
}


MainActivity..

public void MakePost(final PostModel postModel){
new AsyncTask<Void,Void,Void>(){
@Override
protected Void doInBackground(Void... params) {
try {
PostBase postBase = new PostBase();
statusCode = postBase.POST(postModel);
if(statusCode == 201){
//TODO
}else {
//TODO
}
} catch (IOException e) {
e.printStackTrace();

}
return null;
}
}.execute();
}

Answer

https://developer.android.com/reference/android/os/AsyncTask.html

onPreExecute and onPostExecute run on the ui thread while you cannot update ui from doInBackground as it runs on a background thread

So display dialog in onPreExecute and dismiss dialog in onPostExecute

Return some value in doInBackground and do what is necessary in onPostExecute based on the value returned.

If you want to show progress of the upload you can do that using onProgressUpdate

new AsyncTask<Void,Void,String>(){

    @Override
    protected void onPreExecute()
    {
      super.onPreExecute()
      // runs on the ui thread
      // show dialog
    }  
    @Override
    protected String doInBackground(Void... params) {
        try {
            PostBase postBase = new PostBase();
            statusCode = postBase.POST(postModel);
            if(statusCode == 201){
              return "successful";
            }else {
              return "notsuccessful"
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        return "something";
    }

    @Override
    protected void onPostExecute(String result)
    {
      super.onPostExecute();
      // dismiss dialog
      if(result.equals("successful")
      {
        // do something on successful
        // runs on the ui thread so do update ui
      }
    }   
}.execute();

Apart from the asynctask code it looks like you are using Retrofit. You can also make asynchronous calls with the same.

Comments