私はこのコードを持っていますが、AndroidEmulator4.2では次のエラーが発生します。networkonmainthreadexception null
私は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();
}
});