سؤال

I have this code but in my Android Emulator 4.2 I get the follow error: networkonmainthreadexception null

I am new to Android and this is my first application, I have a web-view and after I need download a PDF and save in SD-card.

This is my Code:

browser.setDownloadListener(new DownloadListener()
        {
            public void onDownloadStart(final String url, String userAgent, String contentDisposition, String mimetype, long contentLength)
            {               
                AlertDialog.Builder builder = new AlertDialog.Builder(WebViewdemoActivity.this);
                builder.setTitle("Descarga");
                builder.setMessage("¿Desea guardar el fichero en su tarjeta SD?");
                builder.setCancelable(false).setPositiveButton("Aceptar", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        descargar(url);
                    }

                }).setNegativeButton("Cancelar", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        dialog.cancel();
                    }
                });
                builder.create().show();                


            }

            private void descargar(final String url)
            {
           String resultado ="";

                //se obtiene el fichero con Apache HttpClient, API recomendada por Google
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                InputStream inputStream = null;
                try
                {
                    HttpResponse httpResponse = httpClient.execute(httpGet);

                    BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpResponse.getEntity());

                    inputStream = bufferedHttpEntity.getContent();

                    //se crea el fichero en el que se almacenará
                    String fileName = android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/webviewdemo";
                    File directorio = new File(fileName);
                    File file = new File(directorio, url.substring(url.lastIndexOf("/")));
                    //asegura que el directorio exista
                    directorio.mkdirs();                    

                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                    byte[] buffer = new byte[1024];

                    int len = 0;
                    while (inputStream.available() > 0 && (len = inputStream.read(buffer)) != -1)
                    {
                        byteArrayOutputStream.write(buffer, 0, len);
                    }
                    fileOutputStream.write(byteArrayOutputStream.toByteArray());
                    fileOutputStream.flush();
                    resultado = "guardado en : " + file.getAbsolutePath();
                }
                catch (Exception ex)
                {
                    resultado = ex.getClass().getSimpleName() + " " + ex.getMessage();
                }
                finally
                {
                    if (inputStream != null)
                    {
                        try
                        {
                            inputStream.close();
                        }
                        catch (IOException e)
                        {

                        }
                    }
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(WebViewdemoActivity.this);
                builder.setMessage(resultado).setPositiveButton("Aceptar", null).setTitle("Descarga");
                builder.show();

            }

        });
هل كانت مفيدة؟

المحلول

You need to move the part of the network connection to a separate thread, better using AsyncTask..

ex:

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }

}

نصائح أخرى

You need to perform network operation on a secondary thread, either create a new thread or use the more appropriate method: AsyncTask. http://developer.android.com/reference/android/os/AsyncTask.html

This will perform the action on another thread instead of locking the main/UI thread.

From official documentation :

This (NetworkOnMainThreadException) is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

Link : http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

You are trying to connect internet on a main thread which is not supportable by Android 4.0. You should connect to internet in AysnchTask.. For more details you can take help from following tutorials..

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

http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/

I am sure you will get something from it. Try it.!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top