Android ProgressDialog does not appear

4

I'm trying to show a ProgressDialog in the process of downloading a binary file, however it does not appear, and I do not get any error as well. Briefly explain how I have structured code

In my MainActivity I define a button to get this file ... When we click on the button whose name is botao_getbscan, an AlertDialog appears, with a series of parameters for the user to define, in order to construct a string that represents the URL to download binary file. After setting these parameters the user clicks on the ok button of AlertDialog and it disappears, starting to download, as you can see below:

botao_getbscan = (Button)findViewById(R.id.button4);
botao_getbscan.setOnClickListener(new View.OnClickListener() {
@Override
        public void onClick(View arg0) {

            // Se houver internet avança...
            if (isNetworkAvailable()) {
                // Construção de um dialog para introduzir os valores de contrução do b-scan
                LayoutInflater li = LayoutInflater.from(mContext);
                View dialog_view = li.inflate(R.layout.getbscan_dialog,null);
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
                alertDialogBuilder.setView(dialog_view);

                // Define o titulo e a mensagem do dialog
                //(...)

                // Define os botões do dialog
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                       //Definição de uma série de parâmetros para construir uma string com o "GET" pretendido...
                                       final String fullstring = "http://...................................;

                                       // Inicia o download e armazena na memória interna...
                                       boolean succed = StartDownload(fullstring);

                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                // Cria e mostra o alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
            else {
                AlertDialog.Builder saveDialog = new AlertDialog.Builder(MainActivity.this);
                saveDialog.setTitle("No Internet Connection Detected");
                saveDialog.setMessage("A connection to the internet is required to retrieve B-Scan. Please check your connection settings and try again.");
                saveDialog.setNeutralButton("OK",
                        new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,int id) {
                        dialog.dismiss();
                    }
                });
                saveDialog.show();
            }
        }
    });//End of Get B-Scan Button

The StartDownload method consists of the following:

public boolean StartDownload(String string){
    BitmapDownloaderTask object = new BitmapDownloaderTask(MainActivity.this);
    object.execute(string);
    try {
        byteArray = object.get();
        return true;
    } catch (Exception e) {
        Log.e("saveToInternalStorage()", e.getMessage());
        return false;
    }
} // End of StartDownload

Next I have my AsyncTask in a different file than the one I called BitmapDownloaderTask.java, which basically defines my BitmapDownloaderTask class that extends an AsyncTask. This is where I define the progress dialog, which I would like to appear after clicking on the OK button of my AlertDialog, since after this the download process starts immediately. However the progress dialog does not appear and I also do not get any error . I then have the following:

class BitmapDownloaderTask extends AsyncTask<String, Void, byte[]> {

private ProgressDialog dialog;
private Context context;
private byte[] byteArray;

//--------------------CONSTRUCTOR--------------------------------//
public BitmapDownloaderTask(Context context) {
    this.context = context;
    this.byteArray = null;
    dialog = new ProgressDialog(context);
}

//--------------PRE EXECUTE--------------------------------------//
@Override
protected void onPreExecute() {
    super.onPreExecute();

    dialog.setMessage("Loading...");
    dialog.show();
}


//--------------BACKGROUND---------------------------------------//
@Override
// Actual download method, run in the task thread
protected byte[] doInBackground(String... params) {

    // params comes from the execute() call: params[0] is the url.
    return downloadBitmap(params[0]);
}


//--------------POST EXECUTE-------------------------------------//
@Override
// Once the image is downloaded
protected void onPostExecute(byte[] byteArray) {
    super.onPostExecute(byteArray);
    dialog.dismiss();
    if(byteArray != null){
        //pDialog.dismiss();
    }else{
        //pDialog.dismiss();
        Toast.makeText(this.context,"B-scan doens't exist, or there was a connection problem!", Toast.LENGTH_SHORT).show();
    }
}

static byte[] downloadBitmap(String url) {
// ......................
}

Thank you!

    
asked by anonymous 25.06.2015 / 14:36

2 answers

2

The reason this happens is due to the method call get () of the AsyncTask class in the StartDownload() method.

public boolean StartDownload(String string){
    BitmapDownloaderTask object = new BitmapDownloaderTask(MainActivity.this);
    object.execute(string);
    try {
        byteArray = object.get();
        return true;
    } catch (Exception e) {
        Log.e("saveToInternalStorage()", e.getMessage());
        return false;
    }
} // End of StartDownload

This method locks up the UIThread while the AsyncTask runs.

The dialog.show(); method is called in onPreExecute() but as UIThread is locked the Dialog can not be displayed.

At the time the UIThread is unlocked, the onPosExecute() method has already been called and the dialog.dismiss() line is executed.

It does not make sense to use an AsyncTask and then wait for it to end in UIThread .

Drop the call to the get() method and treat the Download result within the onPostExecute(); method or, within that method, call an Activity method that do it.

Implementation of BitmapDownloaderTask .

As BitmapDownloaderTask resides in a file itself, we will have to pass in the constructor the class that contains the method that will handle the result.

So that it can be used with any Activity besides the MainActivity , we declare an interface that should be implemented by it (Activity).

class BitmapDownloaderTask extends AsyncTask<String, Void, byte[]> {

    // Interface a ser implementada pela classe consumidora
    public interface OnDownloadFinishedListener{
        public void onDownloadFinished(byte[] resultado);
    }

    private ProgressDialog dialog;
    private Context context;
    private OnDownloadFinishedListener listener;
    private byte[] byteArray;

    //--------------------CONSTRUCTOR--------------------------------//
    public BitmapDownloaderTask(Activity activity) {

        this.context = activity;

        //Verifica se a Activity passada implementa a interface
        if(activity instanceof OnDownloadFinishedListener){
            this.listener = (OnDownloadFinishedListener)activity;
        }
        else{
            throw new ClassCastException(activity.toString()
                      + " must implement OnDownloadFinishedListener");
        }
        this.byteArray = null;
        dialog = new ProgressDialog(context);
    }

    //--------------PRE EXECUTE--------------------------------------//
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        dialog.setMessage("Loading...");
        dialog.show();
    }


    //--------------BACKGROUND---------------------------------------//
    @Override
    // Actual download method, run in the task thread
    protected byte[] doInBackground(String... params) {

        // params comes from the execute() call: params[0] is the url.
        return downloadBitmap(params[0]);
    }


    //--------------POST EXECUTE-------------------------------------//
    @Override
    // Once the image is downloaded
    protected void onPostExecute(byte[] byteArray) {

        dialog.dismiss();

        //Se houver um resultado
        //Chammos o método da interface(Activity)
        if(byteArray != null){
            listener.onDownloadFinished(byteArray);
        }else{
            Toast.makeText(this.context,"B-scan doens't exist, or there was a connection problem!", Toast.LENGTH_SHORT).show();
        }
    }

    static byte[] downloadBitmap(String url) {
        // ......................
    }
}

Make MainActivity implement the interface:

public class MainActivity extends ActionBarActivity implements OnDownloadFinishedListener{

    ..........
    ..........
    ..........
    ..........
    @Override
    public void onDownloadFinished(byte[] resultado) {

        //Faça aqui o tratamento do resultado
    }
}

The StartDownload() method will look like this:

public void StartDownload(String string){
    BitmapDownloaderTask object = new BitmapDownloaderTask(this);
    object.execute(string);

} // End of StartDownload

Note: The method returns nothing

    
25.06.2015 / 16:15
0

Your code is right, check if it is passing through this section:

    //--------------PRE EXECUTE--------------------------------------//
    @Override
    protected void onPreExecute() {
       super.onPreExecute();

       dialog.setMessage("Loading...");
       dialog.show();
    }

If it is not happening, it will run in the background so you can not see the load, an alternative is you put your Progress Dialog into just the onClick.

    
25.06.2015 / 14:50