2012-12-17 69 views
-3

我有這樣的代碼,但在我的Android模擬器4.2我得到了如下錯誤:networkonmainthreadexception null錯誤networkonmainthreadexception空

我是新來的Android,這是我的第一個應用程序,我有一個Web視圖後,我需要下載一個PDF並保存在SD卡中。

這是我的代碼:

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

      } 

     }); 
+0

不要在主線程中調用網絡操作,在後臺線程中執行! – Carnal

+0

你應該在線程或AsyncTask中調用網絡。從3.0開始,主線程不支持網絡調用。 –

回答

2

你需要移動網絡連接到一個單獨的線程的一部分,更好地利用AsyncTask ..

例如:

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

}

相關問題