publishProgress only updates Progress Dialog at the end of doBackgorund

0

I am not able to update the progress of my progress dialog during the process of inserting into the SQlite database from a JSON array.

The process occurs without problems, however, the update only happens at the end, when the insertion is finished.

My AsyncTask

public class AtualizaCatalogoJSON extends AsyncTask<Void, Integer, Void> 

{

    Context context;
    UrlList urlList = new UrlList();
    private String urlBuscaMusicas = urlList.urlBuscarMusicas() + 7222;
    private String urlQtdMusicas = urlList.urlQtdMusicas();
    private ProgressDialog pDialog;

    public AtualizaCatalogoJSON(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(context);
        pDialog.setTitle("Qualquer coisa");
        pDialog.setMessage("Mensagem");
        pDialog.setProgressStyle(pDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.setMax(100);
        pDialog.setProgress(0);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        GetJsonArray gs = new GetJsonArray();
        gs.getString(urlBuscaMusicas, new VolleyCallback() {
            @Override
            public void onSuccess(final JSONArray result) {

                try {

                    for (int i = 0; i < result.length(); i++){

                        //insere dados no banco

                        publishProgress((int)(i*100/result.length()));
                    }
                    dao.close();


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        pDialog.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        pDialog.dismiss();
    }


}

As it is now, when calling the task a progress dialog appears and gets stuck at 0, so apparently after running it it is updated.

    
asked by anonymous 01.10.2016 / 01:16

1 answer

0

The getString() method of GetJsonArray is asynchronous. When the onSuccess() method is called, the onPostExecute() method of AsyncTask has already been executed.

It does not make sense to run an asynchronous ( getString() ) method inside an AsyncTask .

However, it makes sense for the bank to be inserted asynchronously.

Put the code that is within the onSeccess() within an AsyncTask and control the ProgressBar in it.

    
01.10.2016 / 13:41