开发者

Android async task download failed err

开发者 https://www.devze.com 2023-04-12 22:58 出处:网络
I\'ve developed an application that takes content from the internet and shows it accordingly on the device\'s screen . The program works just fine , a little bit slow . It takes about 3-4 seconds to l

I've developed an application that takes content from the internet and shows it accordingly on the device's screen . The program works just fine , a little bit slow . It takes about 3-4 seconds to load and display the content . I would like to put my code that does all the work ( grabbing web content and displaying it) in a background thread . Also , I'd like to show a progress dialog .

public class Activity1 extends Activity
{
    private ProgressDialog progressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        new AsyncTask<Integer, Integer, Boolean>()
        {
            ProgressDialog progressDialog;

            @Override
            protected void onPreExecute()
            {
                /*
                 * This is executed on UI thread before doInBackground(). It is
                 * the perfect place to show the progress dialog.
                 */
                progressDialog = ProgressDialog.show(Activity1.this, "",
                        "Loading...");
            }

            @Override
            protected Boolean doInBackground(Integer... params)
            {
                if (params == null)
                {
                    return false;
                }
                try
                {
                    /*
                     * This is run on a background thread, so we can sleep here
                     * or do whatever we want without blocking UI thread. A more
                     * advanced use would download chunks of fixed size and call
                     * publishProgress();
                     */
                    Thread.sleep(params[0]);
                    // HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
                }
                catch (Exception e)
                {
                    Log.e("tag", e.getMessage());
                    /*
                     * The task failed
                     */
                    return false;
                }

                /*
                 * The task succeeded
                 */
                return true;
            }

            @Override
            protected void onPostExecute(Boolean result)
            {
                progressDialog.dismiss();
                /*
                 * Update here your view objects with content from download. It
                 * is save to dismiss dialogs, update views, etc., since we are
                 * working on UI thread.
                 */
                AlertDialog.Builder b = new AlertDialog.Builder(Activity1.this);
                b.setTitle(android.R.string.dialog_alert_title);
                if (result)
                {
                    b.setMessage("Download succeeded");
                }
                else
                {
                    b.setMessage("Download failed");
                }
                b.setPositiveButton(getString(android.R.string.ok),
                        new DialogInterface.OnClickListener()
                        {

                            @Override
                            public void onClick(DialogInterface dlg, int arg1)
                            {
                                dlg.dismiss();
                            }
                        });
                b.create().show();
            }
        }.execute(2000);

      /*  new Thread()
        {
            @Override
            public void run()
            {

                // dismiss the progressdialog
       开发者_C百科         progressDialog.dismiss();
            }
        }.start();
    }*/
}

If I run the application with this code , I get this : download failed . On the other hand , if I keep the final thread , the app crashes , NullPointerException . I really don't know what to do anymore .

I would really appreaciate if you could give me an alternative to this code , not just some hints because I'm new to android and I really don't know much . Thanks.

UPDATE :

I don't want to display the progress of the download , I want to display the progress dialog until the app is ready to display the full content.


The best approach to do this is by using the AsyncTask class, as it will allow you to execute some background process and update the UI at the same time (in your case, it's a progress bar).

This is an example code:

ProgressDialog mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");

The AsyncTask will look like this:

private class DownloadFile extends AsyncTask<String, Integer, String>{
    @Override
    protected String doInBackground(String... url) {
        int count;
        try {
            URL url = new URL(url[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            // this will be useful so that you can show a tipical 0-100% progress bar
            int lenghtOfFile = conexion.getContentLength();

            // downlod the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.ext");

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                publishProgress((int)(total*100/lenghtOfFile));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {}
        return null;
    }

The method above (doInBackground) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate runs on the UI thread, so there you will change the progress bar:

@Override
public void onProgressUpdate(String... args){
    // here you will have to update the progressbar
    // with something like
    mProgressDialog.setProgress(args[0]);
}

} You will also want to override the onPostExecute method if you want to execute some code once the file has been downloaded completely.


You should create an inner class for AsyncTask like this :

private class YourTask extends AsyncTask<Context, Void, Void>
{

ProgressDialog dialog = new ProgressDialog(mContext);

    protected void onPreExecute()
    {
       dialog.setMessage("loading..");
       dialog.show();
    }

    protected Void doInBackground(Context... params)
    {

                   // ...


        return null;
    }

    protected void onPostExecute(final Void unused)
    {
        dialog.dismiss();
    }
}

and in onCreate() put :

     new YourTask().execute();

and for more detail you should check this once:

http://developer.android.com/reference/android/os/AsyncTask.html


When you use the new thread, your app crashes because the progress dialog is not initialized there

Inside your new thread use:

`progressDialog = ProgressDialog.show(Activity1.this, "","Loading...");

and about that alert dialog: Basically either params is null or the logic is throwing some exception. It's not returning true so check the ddms logs and post them here.

`

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号