Atlas91
Atlas91

Reputation: 5904

AsyncTask not showing dialog during operation

The progressDialog of my AsyncTask not showing. It seems correct but it doesn't display the dialog.. The operations inside works perfectly but seems ignoring the onPreExecute() and onPostExecute() methods..

private class copyApk extends AsyncTask<Void, Void, Void> {

    int appPosition;
    ProgressDialog mProgressDialog = new ProgressDialog(getActivity());


    @Override
    protected void onPreExecute(Void pre) {
        super.onPreExecute();

        mProgressDialog.setTitle("Copy apk");
        mProgressDialog.setMessage("Copying...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }



    @Override
    protected Void doInBackground(Void... apks) {
        final File customfolder = new File(Environment.getExternalStorageDirectory().toString()+File.separator+"HazyApkBackup");
        if(!customfolder.exists()){
            customfolder.mkdirs();
        }
        try
        {

            vacca = getActivity().getPackageManager().getApplicationInfo(app.getPackageName(), packageManager.GET_META_DATA).sourceDir.toString();
            //Toast.makeText(getActivity(), "Boh "+vacca, Toast.LENGTH_SHORT).show();
            process = Runtime.getRuntime().exec("cp " + vacca + " " + customfolder);
            //Toast.makeText(getActivity(), "Apk copied in "+customfolder, Toast.LENGTH_SHORT).show();
        }
        catch (PackageManager.NameNotFoundException | IOException e)
        {
            Toast.makeText(getActivity(), "Sorry, the apk was not copied correctly", Toast.LENGTH_SHORT).show();
        }       

        return null;
        }

    @Override
    protected void onPostExecute(Void result) {
    super.onPostExecute(result);

        if(mProgressDialog.isShowing())
        Toast.makeText(getActivity(), "Apk copied in "+customfolder, Toast.LENGTH_SHORT).show();
        mProgressDialog.dismiss();  

    }
}

Thanks

Upvotes: 1

Views: 72

Answers (2)

Sagar D
Sagar D

Reputation: 2618

The prototype of onPreExecute() :

@Override
    protected void onPreExecute() {

}

The onPreExecute() and onPostExecute() methods are called on the UI thread. It is always better to use a WeakReference to avoid exceptions in future.

In your AsyncTask, create a WeakReference like :

private WeakReference<MyActivity> myWeakContext;

Then in your onPreExecute(),

MyActivity activity = this.myWeakContext.get();
ProgressDialog mProgressDialog = new ProgressDialog(activity);

Upvotes: 0

Mike M.
Mike M.

Reputation: 39201

Your onPreExecute() method isn't getting called, as it has the incorrect signature. The correct method has no parameters.

@Override
protected void onPreExecute()
{
    ...

Upvotes: 1

Related Questions