publishProgress only updates the Progress Dialog at the end of theInBackgorund

Asked

Viewed 124 times

0

I am unable to update the progress of my Progress dialog during the insertion process into the Sqlite database from a JSON array.

The process occurs smoothly, however, the update only happens at the end, when the insertion ends.

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 the Progress dialog appears and is stopped at 0, then apparently after all is run it is updated.

1 answer

0


The method getString() of Getjsonarray is asynchronous. When the method onSuccess() is called, already the method onPostExecute() of Asynctask was executed.

No sense running an asynchronous method(getString()) within a Asynctask.

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

Put the code inside the onSeccess() within a Asynctask and control the Progressbar in it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.