我正在尝试使用以下asynctask方法从网址加载图片(JPG)。
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
我正在onCreate中执行此方法,就像这样
new DownloadImageTask((ImageView) findViewById(R.id.imageView1)).execute(final_url);
但是我看不到任何图像,当我调试它时,我发现mIcon11
的值为null。我做错了什么
PS:final_url
就像这样
www.website.com/somelink/IMG 005_153.JPG
答案 0 :(得分:0)
你的finalurl http://www.website.com/somelink/IMG%20005_153.JPG
没有返回任何东西。检查..
在使用之前尝试对其进行编码。
String uri = Uri.parse("http://...")
.buildUpon()
.appendQueryParameter("key", "val")
.build().toString();
或尝试以下
String uri = URLEncoder.encode(finalurl,“utf-8”);
答案 1 :(得分:0)
private class ImageLoadTask extends AsyncTask<String, Void, Bitmap> {
private Bitmap bitmap;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pb1.setVisibility(View.VISIBLE);
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
try {
URL url;
url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
im.setImageBitmap(result);
pb1.setVisibility(View.INVISIBLE);
}
}
并将其称为
new ImageLoadTask().execute(STRING URL);