Extracting File with Progressdialog

Asked

Viewed 88 times

1

Hello, I need to implement the `Progressdialog while the file is being extracted.

My extraction code is following. Now just implement ProgressDialog, recalling that the downloaded code has already been tried to be implemented the ProgressDialog for me, but it didn’t work, he gets the feather Toast:

private Button et1;
private ProgressDialog pDialog;

...
et1 = (Button) findViewById(R.id.btn1);

pDialog = new ProgressDialog(this);
pDialog.setMessage("Extraindo arquivo...");
pDialog.setCancelable(false);

et1.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v1){
        etap1();    
    }
});

...

public void etap1(){
    showpDialog(); <--

    String zipFilePath = Environment.getExternalStorageDirectory() 
    .getAbsolutePath()+"/"; 
    unpackZip(zipFilePath, "arquivo.zip"); 
} 

private boolean unpackZip(String path, String zipname) { 
    InputStream is; 
    ZipInputStream zis; 
    try {
        String filename; 
        is = new FileInputStream(path + zipname); 
        zis = new ZipInputStream(new BufferedInputStream(is)); 
        ZipEntry mZipEntry; byte[] buffer = new byte[1024]; 
        int count; 
        while ((mZipEntry = zis.getNextEntry()) != null) { 
            filename = mZipEntry.getName(); 

            if (mZipEntry.isDirectory()) { 
                File fmd = new File(path + filename); 
                fmd.mkdirs(); 
                continue; 
            } 
            FileOutputStream fout = new FileOutputStream(path + filename); 
            while ((count = zis.read(buffer)) != -1) { 
                fout.write(buffer, 0, count); 
            } 
            fout.close(); zis.closeEntry(); 
            Toast.makeText(getApplicationContext(), "Extraído com sucesso", 
                           Toast.LENGTH_SHORT).show(); 
        }

        hidepDialog(); <--
        zis.close(); 
    } catch (IOException e) { e.printStackTrace(); 
        return false; 
    } 

    hidepDialog(); <--
    return true; 
}

private void showpDialog() { <--
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hidepDialog() { <--
    if (pDialog.isShowing())
        pDialog.dismiss();
}

The file is extracted smoothly, there are no errors in the extraction code, only the ProgressDialog who does not appear.

Someone can help me find the mistake?

Thank you!

1 answer

1


Good afternoon friend.

What may be happening is that your file extraction process, running on main thread (UI Thread), should be harming the screen update, "freezing" the screen, then your dialog is not displayed.

I suggest you do the extraction at thread the part, so you can leave the main thread in charge of displaying your dialog.

A great alternative to work with threads on Android is the use of class Asynctask.

All extraction logic the part which extends the Asynctask class.

In this class you can override the following methods:

  • doInBackground: here is the code responsible for extracting your file;
  • onPreExecute: here is the code that will be executed before the extraction process starts, for example, display the dialog here;
  • onPostExecute: in this method the code for execution after the end of the process, for example hide the dialog;

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

An example to help you understand better:

// classe que extrai o arquivo e estente AsyncTask
public class ExtrairTask extends AsyncTask<Void, Void, Void> {

    // variável do dialog
    private ProgressDialog pDialog;

    // construtor padrão
    public ExtrairTask() {

        // instanciando o dialog
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Extraindo arquivo...");
        pDialog.setCancelable(false);
    }

    @Override
    protected Void doInBackground(Void... params) { 
        /*
            aqui vai o código para extrair o  arquivo... 
            ele pode ser implementando aqui ou pode ser feita a chamada de uma função
        */
    }

    @Override
    protected void onPreExecute() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

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

}

// sua activity, onde o usuário executa a ação para extrair o arquivo
public class MainActivity extends Activity {

    // variável da sua tarefa de extração
   private ExtrairTask et;

   public void extrairArquivo(View v) {

        // em resposta a uma ação do usuário, instanciamos a tarefa e executamos
        et = new ExtrairTask
        et.execute();
   }

}

NOTE: the code was not compiled, as it was added only as an example for better understanding.

  • Hello friend, exactly that. The screen is freezing, give a lock exactly at the time of extraction. I’ll get more on the Asynctask class, thank you very much!

  • Friend, I added an example in the answer for better understanding.

  • Friend, what a wonder ... Thank you very much, happy one here. But so, what if I want to perform two tasks at once, you know how it does? Ex: After extracting the file, I want to delete it. Doing both at once, is it complicated? Remembering that I already have the exclusion code, I just don’t know how to determine first to extract and then delete. Thank you so much again, you don’t know how much it helped me.

  • 1

    If the two tasks can be performed in sequence, you can place everything within the same thread, calling the extraction method and in the deletion sequence, all within the doInBackground. Now, if you want to do an Asynctask for each operation you should know that the procedures will be asynchronous, so simply calling one after the other (with the method execute) in the main Activity does not guarantee that they will be executed, in practice, one after the other.

Browser other questions tagged

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