Android Progressdialog does not appear

Asked

Viewed 837 times

4

I am trying to show a Progressdialog in the process of downloading a binary file, however this does not appear, and I get no error either. I will briefly explain the way I have structured code

In my Mainactivity I set a button to get that file... When we click on the button whose name is botao_getbscan, we see a Alertdialog, with a series of parameters for the user to define, in order to build a string that represents the URL to download the binary file. After setting these parameters the user presses 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 which I called Bitmapdownloadertask.java, which basically defines my Bitmapdownloadertask class which extends an Asynctask. This is where I set up the Progress dialog, which I would like to appear after clicking on the OK button of my Alertdialog, since after that the Download process starts immediately.. However the Progress dialog does not appear and I also get no error. I 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!

  • You implemented something in the method downloadBitmap()?

  • @ramaral Sim implementei, is a simple download method from a url using Httpentity Httpresponse and Inputstream...

2 answers

2


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

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 blocks the Uithread as long as the Asynctask is executed.

The method dialog.show(); is called in the onPreExecute() but like the Uithread is blocked the Dialog cannot be presented.

At the time when the Uithread is unlocked, already the method onPosExecute() was called and the line dialog.dismiss() executed.

No sense wearing a Asynctask and then stay waiting that it ends within the Uithread.

Call out the method get() and treat the outcome of Download within the method onPostExecute(); or, within it, call a method of Activity do so.

Implementation of Bitmapdownloadertask.

Like Bitmapdownloadertask resides in a proper file, we have to pass, in constructor, the class containing the method that will handle the output.

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) {
        // ......................
    }
}

Have 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 method StartDownload() it will be so:

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

} // End of StartDownload

Note: The method returns nothing

  • I understood what you said, but the Startdownload method just calls Asynctask, and then with Object.get() i get the byte array that represents the download result from async task... I don’t see how else to do it... I need that byte array in my Mainactivity... could explain me how to do it in onPostExecute()?

  • 1

    The class Bitmapdownloadertask is stated in the Activity or is in a file of its own?

  • is in a file of its own... file that contains the Bitmapdownloadertask class that extends Asynctask, and also contains the Static byte[] downloadBitmap(String url) method that is responsible for downloading the byte array. Thank you!

  • 1

    I edited the answer.

  • Thank you very much! I managed to implement your solution, great help even :D

0

Your code is right, make sure it’s going through that stretch:

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

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

If you’re not passing, it will run in the background so you can’t see the load, an alternative is to put your Progress Dialog inside onClick only.

  • 1

    If the dialog.show();is placed in the onClick() where the dialog.dismiss();?

  • @Leonardo Rocha in concrete how he put the dialog.show in onClick? created the object in my Mainactivity? is that I have asynctask in another file and not in the onClick file that is the Mainactivity class. It would be something like before botao_getbscan.setOnClickListener(new View.Onclicklistener() created the object to type progressdialog and then inside onClick would put dialog.show()? and where would be the dialog.Ismiss(), as said the ramaral... Thank you!

  • @Leonardo Rocha I forgot to mention that the program passes in onPreExecute(), I checked through Logs and debugging...

  • You must create the progressdialog object and within onClick put the dialog.show(), the dialog,.

Browser other questions tagged

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