Search code examples
androidnetworkonmainthread

Error networkonmainthreadexception null


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();

            }

        });

Solution

  • 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");
     }
    

    }