从互联网下载一个图片文件,Android上的Java在AndroidStudio中工作
我想用AndroidStudio创建一个非常简单的应用程序,从互联网下载一个图像文件,但它根本不起作用。我什么都试过了,查过代码,在网上查过类似的问题,试过各种各样的图片大小和格式。但我总是在代码的底部得到错误消息。代码如下: 第二个问题:我如何在IntentService类的帮助下重写同样的代码?如果您能回答其中任何一个问题,我们将不胜感激从互联网下载一个图片文件,Android上的Java在AndroidStudio中工作,java,android-studio,download,Java,Android Studio,Download,我想用AndroidStudio创建一个非常简单的应用程序,从互联网下载一个图像文件,但它根本不起作用。我什么都试过了,查过代码,在网上查过类似的问题,试过各种各样的图片大小和格式。但我总是在代码的底部得到错误消息。代码如下: 第二个问题:我如何在IntentService类的帮助下重写同样的代码?如果您能回答其中任何一个问题,我们将不胜感激 try{ URL fileurl = new URL(urlstring); URLConnection urlC
try{
URL fileurl = new URL(urlstring);
URLConnection urlConnection = fileurl.openConnection();
urlConnection.connect();
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream(), 9200);
File downloadordner = new File(Environment.getExternalStorageDirectory(), "Download");
if(!downloadordner.exists()){
downloadordner.mkdirs();
}
File downloadedFile = new File(downloadordner, "myFirstProject" + System.currentTimeMillis()+".png");
OutputStream outputstream = new FileOutputStream(downloadedFile);
byte[] buffer = new byte[1024];
int read;
while((read = inputStream.read(buffer)) != -1){
outputstream.write(buffer, 0, read);
}
outputstream.flush();
outputstream.close();
inputStream.close();
final Bitmap bitmap = BitmapFactory.decodeFile(downloadedFile.getAbsolutePath());
runOnUiThread(new Runnable() {
@Override
public void run() {
image.setImageBitmap(bitmap);
progressDialog.dismiss();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "THIS IS THE ERROR MESSAGE I ALWAYS KEEP GETTING!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
“Download”字符串是智能手机中图片应该存储的目录的名称!如果有人能指出导致此错误消息的原因,我将非常高兴和感激!Thanx:)您能分享报告的错误吗?错误是发生在Android设备上还是在Android emulator中?错误是我在代码的下一行中设置为字符串的消息。错误发生在emulator中,我还没有在设备上测试它。请将错误添加到您的问题中