在android中下载文件:Nullpointerexception

在android中下载文件:Nullpointerexception,android,Android,我正在尝试从android应用程序内部下载一个文件。当代码到达行时 connection.connect(); Logcat显示此异常: 09-23 21:41:21.853: W/System.err(6084): android.os.NetworkOnMainThreadException 09-23 21:41:21.863: W/System.err(6084): at android.os.StrictMode$AndroidBlockGuardPolicy.onNet

我正在尝试从android应用程序内部下载一个文件。当代码到达行时

connection.connect();
Logcat显示此异常:

  09-23 21:41:21.853: W/System.err(6084): android.os.NetworkOnMainThreadException
09-23 21:41:21.863: W/System.err(6084):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
09-23 21:41:21.863: W/System.err(6084):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
09-23 21:41:21.863: W/System.err(6084):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-23 21:41:21.863: W/System.err(6084):     at libcore.io.IoBridge.connect(IoBridge.java:112)
09-23 21:41:21.863: W/System.err(6084):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-23 21:41:21.863: W/System.err(6084):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-23 21:41:21.863: W/System.err(6084):     at java.net.Socket.connect(Socket.java:842)
09-23 21:41:21.863: W/System.err(6084):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:76)
09-23 21:41:21.873: W/System.err(6084):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
09-23 21:41:21.873: W/System.err(6084):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
09-23 21:41:21.873: W/System.err(6084):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
09-23 21:41:21.873: W/System.err(6084):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
09-23 21:41:21.873: W/System.err(6084):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
09-23 21:41:21.873: W/System.err(6084):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
09-23 21:41:21.873: W/System.err(6084):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
09-23 21:41:21.873: W/System.err(6084):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
09-23 21:41:21.873: W/System.err(6084):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
09-23 21:41:21.873: W/System.err(6084):     at com.asde.ipac.AsyncUpdater$1.onClick(AsyncUpdater.java:107)
09-23 21:41:21.883: W/System.err(6084):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
09-23 21:41:21.883: W/System.err(6084):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-23 21:41:21.883: W/System.err(6084):     at android.os.Looper.loop(Looper.java:137)
09-23 21:41:21.883: W/System.err(6084):     at android.app.ActivityThread.main(ActivityThread.java:5103)
09-23 21:41:21.883: W/System.err(6084):     at java.lang.reflect.Method.invokeNative(Native Method)
09-23 21:41:21.883: W/System.err(6084):     at java.lang.reflect.Method.invoke(Method.java:525)
09-23 21:41:21.893: W/System.err(6084):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-23 21:41:21.893: W/System.err(6084):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-23 21:41:21.893: W/System.err(6084):     at dalvik.system.NativeStart.main(Native Method)
这是文件的url:

private String urlDownload = "http://192.168.0.107/ipac/ipac.apk/";
这是方法的代码:

protected void onPostExecute(String lastVer) {

        PackageInfo packageInfo;
        try {
            packageInfo = ((Activity) ctx).getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
            String currentVer = packageInfo.versionName;

            System.out.println("Server: "+ lastVer);
            System.out.println("Installed: "+ currentVer);
            if(!lastVer.equals(currentVer))
            {
                new AlertDialog.Builder(ctx)
                .setTitle("UPDATE AVAILABLE")
                .setMessage("New Test available")
                .setCancelable(false)
                .setPositiveButton("DOWNLOAD", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                         try {
                             System.out.println("0!!!!");
                                URL url = new URL(urlDownload);
                                System.out.println("0.2!!!!");
                                URLConnection connection = url.openConnection();
                                System.out.println("0.3!!!!" + url.toString());
                                connection.connect();
                                System.out.println("1!!!!");
//                              int fileLength = connection.getContentLength();

                                // download the file
                                InputStream input = new BufferedInputStream(url.openStream());
                                OutputStream output = new FileOutputStream(path);
                                System.out.println("2!!!!");
                                byte data[] = new byte[1024];
//                              long total = 0;
                                int count;
                                while ((count = input.read(data)) != -1) {
//                                  total += count;
//                                  publishProgress((int) (total * 100 / fileLength));
                                    output.write(data, 0, count);
                                }
                                System.out.println("3!!!!");
                                output.flush();
                                output.close();
                                input.close();


                                //INSTALL
                            } catch (Exception e) {


                                 e.printStackTrace();
                            }



                    }
                })
                .setNegativeButton("LATER", null)
                .show();    

            }
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }

会发生什么?

您必须在主线程上使用异步任务或线程,否则Android将像您的崩溃一样崩溃

将其置于onCreate(全局变量)之外:

ProgressDialog mProgressDialog;
    mProgressDialog = new ProgressDialog(About.this);
        mProgressDialog.setMessage("Downloading file....");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);


Then make that class:
private class DownloadFile extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... sUrl) {

            File folders = new File(Environment.getExternalStorageDirectory()
                    + "/pathofthefile/");
            folders.mkdirs();

            File file;
            file = new File(Environment.getExternalStorageDirectory()
                    + "/pathofthefile/nameofthefile.extensionofthefile");


            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                file.delete();
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            try {
                URL url = new URL(sUrl[0]);
                URLConnection connection = url.openConnection();
                connection.connect();
                // this will be useful so that you can show a typical 0-100%
                // progress bar
                int fileLength = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(file);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }

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

        }

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

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            mProgressDialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mProgressDialog.dismiss();
            if (result.equals("Downloaded")) {
                //do something here with the downloaded file
            }
        }
    }
DownloadFile downloadFile = new DownloadFile();
                    downloadFile.execute("http://www.page.com/file.mp3");
然后将其放在活动的内部(外部oncreate):

ProgressDialog mProgressDialog;
    mProgressDialog = new ProgressDialog(About.this);
        mProgressDialog.setMessage("Downloading file....");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);


Then make that class:
private class DownloadFile extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... sUrl) {

            File folders = new File(Environment.getExternalStorageDirectory()
                    + "/pathofthefile/");
            folders.mkdirs();

            File file;
            file = new File(Environment.getExternalStorageDirectory()
                    + "/pathofthefile/nameofthefile.extensionofthefile");


            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                file.delete();
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            try {
                URL url = new URL(sUrl[0]);
                URLConnection connection = url.openConnection();
                connection.connect();
                // this will be useful so that you can show a typical 0-100%
                // progress bar
                int fileLength = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(file);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }

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

        }

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

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            mProgressDialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mProgressDialog.dismiss();
            if (result.equals("Downloaded")) {
                //do something here with the downloaded file
            }
        }
    }
DownloadFile downloadFile = new DownloadFile();
                    downloadFile.execute("http://www.page.com/file.mp3");

希望能有所帮助

为什么要在ui线程上调用的
onPostexecute
中执行n/w操作?您在onPostexecute中执行网络事务,这就是工作方式,请在doInBackground中执行所有网络事务,或者不在ui线程中执行自己的线程。请给我们提供这行代码com.asde.ipac.AsyncUpdater$1.onClick(AsyncUpdater.java:132)@Raghunandan:the's not in
onPostExecute
,它在
onClick
(尽管这一点仍然存在)@njzk2按钮点击在
onPostExecute
内,所以我不想详细提及是的,但不是。onPostExecute完成后执行onClick,并且它在ui线程上执行的事实只与onClick的性质有关,而与它在onPostExecute中声明的事实无关。为什么不在onPreExecute中实例化mProgressDialog呢?