views:

67

answers:

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();
}
+1  A: 

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

Cristian
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
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
I resolved the problem ,thanks.