1

In "onCreate" I'm downloading data from web.The duration of downloading data is 10 sec. I wan't to have ProgressDialog while the data is downloading. Here is my code , but the ProgressDialog doesn't appear:

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ProgressDialog dialog = ProgressDialog.show(Test.this, "", 
        "Loading. Please wait...", true);

     try {
         URL myURL = new URL("http://www.sample.com/");
         URLConnection ucon = myURL.openConnection();
         InputStream is = ucon.getInputStream();
         BufferedInputStream bis = new BufferedInputStream(is);
         ByteArrayBuffer baf = new ByteArrayBuffer(50);
         int current = 0;
          while((current = bis.read()) != -1){
                  baf.append((byte)current);
          }

          content= new String(baf.toByteArray());

     }
     catch (Exception e) {}
     dialog.dismiss();
}
Cristian
  • 198,401
  • 62
  • 356
  • 264
user345602
  • 578
  • 1
  • 12
  • 26

1 Answers1

1

The best approach to do this kind of things is using AsyncTask in order to not freeze the application while you are downloading the file. Moreover, what if you give your users a better experience by using a progress bar dialog rather than a simple dialog. It's not difficult to implement; you can see an example here: Download a file with Android, and showing the progress in a ProgressDialog

Community
  • 1
  • 1
Cristian
  • 198,401
  • 62
  • 356
  • 264
  • Thank you this is great. But in my case i shouldn't use class that extends form AsyncTask, I need to use which extends from Activity. Can I do that to not freeze my app with activity extends? I need only simple dialog without progressbar . Thanks – user345602 Jun 26 '10 at 12:09
  • Of course! You will always need an `Activity`. In this case, the class that extends `AsyncTask` is a private class inside your activity. In the example I didn't write the activity code to focus on what's important in this case: the `AsyncTask` – Cristian Jun 26 '10 at 14:34
  • 1
    make another class extending AsyncTask<> and call it using new asyncTaskClass().execute();, in onPreExecute, show Progressdialog and hide it on onPostExecute – AshuKingSharma Oct 06 '15 at 19:07