26

When I use my code in one class file, it runs perfectly:

package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class DownloadFile extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;
    private static String fileName = "yo.html";
    private static String fileURL = "http://example.com/tabletcms/tablets/tablet_content/000002/form/Best%20Form%20Ever/html";

     @Override
     public void onCreate(Bundle savedInstanceState) 
     {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        TextView tv = new TextView(this);
        tv.setText("This is download file program with asynctask... ");
        tv.append("\nYo, this line is appended!");

        startDownload();

     }

    private void startDownload() {
        new DownloadFileAsync().execute(fileURL);
    }


    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }


    class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
        protected String doInBackground(String... aurl) {

            try {
                File root = Environment.getExternalStorageDirectory();
                URL u = new URL(fileURL);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();

                int lenghtOfFile = c.getContentLength();

                FileOutputStream f = new FileOutputStream(new File(root + "/download/", fileName));

                InputStream in = c.getInputStream();

                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;

                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    publishProgress("" + (int)((total*100)/lenghtOfFile));
                    f.write(buffer, 0, len1);
                }
                f.close();
            } catch (Exception e) {
                Log.d("Downloader", e.getMessage());
            }

            return null;

        }

        protected void onProgressUpdate(String... progress) {
             Log.d("ANDRO_ASYNC",progress[0]);
             mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
    }
}

I want to run the asyntask I have from a different class file, I have my code:

DownloadFile.java

package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class DownloadFile extends Activity {


    private static String fileName = "yo.html";
    private static String fileURL = "http://example.com/tabletcms/tablets/tablet_content/000002/form/Best%20Form%20Ever/html";

     @Override
     public void onCreate(Bundle savedInstanceState) 
     {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        TextView tv = new TextView(this);
        tv.setText("This is download file program with asynctask... ");
        tv.append("\nYo, this line is appended!");

        startDownload();

     }

    private void startDownload() {
        new DownloadFileAsync().execute(fileURL);
    }

}

DownloadFileAsync.java

package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

class DownloadFileAsync extends AsyncTask<String, String, String> {
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {

        try {
            File root = Environment.getExternalStorageDirectory();
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            int lenghtOfFile = c.getContentLength();

            FileOutputStream f = new FileOutputStream(new File(root + "/download/", fileName));

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0) {
                total += len1; //total = total + len1
                publishProgress("" + (int)((total*100)/lenghtOfFile));
                f.write(buffer, 0, len1);
            }
            f.close();
        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }

        return null;

    }

    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }
}

I'm using eclipse and I'm getting errors in my DownloadFile.java file, there are many red underlined codes.... I'm new to java and android dev.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Kris
  • 3,709
  • 15
  • 50
  • 66
  • What actual problem you are getting? can u just provide error description, so that we can help.. – Zoombie May 25 '11 at 03:54
  • Thanks for your response, I just want to separate the DownloadFileAsync class to another class file, when I did, most of the errors I got is something like 'undefined method' – Kris May 25 '11 at 04:00
  • did you try to rebuilfd the project? –  Feb 15 '16 at 08:40

4 Answers4

32

Some changes in your code will make it work :

public class DownloadFileAsync extends AsyncTask<String, String, String> {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;

private Context context;

public DownloadFileAsync(Context context) 
{
    this.context = context;
     mProgressDialog = new ProgressDialog(context);
     mProgressDialog.setMessage("Downloading file..");
     mProgressDialog.setIndeterminate(false);
     mProgressDialog.setMax(100);
     mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     mProgressDialog.setCancelable(true);

}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    mProgressDialog.show();
}

@Override
protected String doInBackground(String... aurl) {

    try {
        File root = Environment.getExternalStorageDirectory();
        URL u = new URL(aurl[0]);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        int lenghtOfFile = c.getContentLength();

        FileOutputStream f = new FileOutputStream(new File(root + "/download/", aurl[1]));

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        long total = 0;

        while ((len1 = in.read(buffer)) > 0) {
            total += len1; //total = total + len1
            publishProgress("" + (int)((total*100)/lenghtOfFile));
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        Log.d("Downloader", e.getMessage());
    }

    return null;

}

protected void onProgressUpdate(String... progress) {
     Log.d("ANDRO_ASYNC",progress[0]);
     mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
    mProgressDialog.dismiss();
}


}

And DownloadFile Class :

public class DownloadFile extends Activity {


private static String fileName = "yo.html";
private static String fileURL = "http://mydomain.com/tabletcms/tablets/tablet_content/000002/form/Best%20Form%20Ever/html";

 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    TextView tv = new TextView(this);
    tv.setText("This is download file program with asynctask... ");
    tv.append("\nYo, this line is appended!");

    startDownload();

 }

private void startDownload() {
    new DownloadFileAsync(this).execute(fileURL,fileName);
}

}
Sadeshkumar Periyasamy
  • 4,848
  • 1
  • 26
  • 31
20

If you can somehow pass the Activity class or its context to the AsyncTask that will solve your issue for showing dialog. You would need to include another parameter together with the URL you are sending and put that parameter in a Context variable. And then whenever you need the dialog you use that context variable to show it.

If the dialog does not have a Context from which to show it will definitely run into runtime errors.

Update (put my comment up here as well): here we go... found a good example that you can modify to make use for your case. It's at brighthub.com/mobile/google-android/articles/82805.aspx. Scroll down to Source Code section and have a look at the code for WebServiceAsyncTask and WebServiceBackgroundActivity.

Gligor
  • 2,862
  • 2
  • 33
  • 40
  • Thanks for your response, but do you have sample code for it? – Kris May 25 '11 at 04:24
  • let me scrabble something out, but it might be tomorrow by the time I post it because I don't have a dev environment here to test it if a code off the top of my head works. I have never ran AsyncTask from a separate file thou so can't promise anything. Only used it as a private class before – Gligor May 25 '11 at 05:36
  • 8
    here we go... found a good example that you can modify to make use for your case. It's at http://www.brighthub.com/mobile/google-android/articles/82805.aspx. Scroll down to Source Code section and have a look at the code for WebServiceAsyncTask and WebServiceBackgroundActivity. – Gligor May 25 '11 at 19:39
  • A little late, but insetad use Object how first parameter, is better create a custom Constructor in you own AsyncTask and pass it your caller Activity and not mix these parameters. – Genaut Jun 17 '19 at 09:44
5

I know its too late to help you but for others this may help.

Its so simple just Simply build an object of main class and than call the inner class like this

 OuterMainClass outer = new OuterMainClass();
       outer.new InnerAsyncClass(param)
         .execute();

Thanks

Syeda Zunaira
  • 5,191
  • 3
  • 38
  • 70
2

Actual problem can be class level error, you might not be placing async class and download class in same package. Other problem I can see is async class using showDialog(), onCreateDialog() etc., which is available only if your class extends Activity.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Zoombie
  • 3,590
  • 5
  • 33
  • 40
  • Thanks for your response, Is it possible to extend the activity at the same time the async task? – Kris May 25 '11 at 03:58
  • No, you cannot extend AsyncTask and Activity same for a single class, as per java rule, a class can extend only one class – Zoombie May 25 '11 at 04:00
  • They are in the same package... hmm is there any other way to make showDialog(), onCreateDialog() etc running in separate class file? – Kris May 25 '11 at 04:03
  • read this [link] http://stackoverflow.com/questions/2379233/android-asynctask-in-external-class – Zoombie May 25 '11 at 04:39
  • With above link example, i tried with your code, it gives me null pointer exception with ` @Override protected void onPreExecute() { super.onPreExecute(); mAct.showDialog(DIALOG_DOWNLOAD_PROGRESS); }` – Zoombie May 25 '11 at 04:43
  • I suggest you to replace showDialog code with creating new dialog every time and use show() method on same.. for example like this: ` mProgessDialog = ProgressDialog.show(FriendsActivity.this, "", resources.getString(R.string.loading_searching_friends), true, false); ` – Zoombie May 25 '11 at 04:44