我在我的Android应用程序中有一个图像视图,我必须从url设置一个简单的图像。我尝试了下面的代码,但它没有设置来自url的图像。从url设置图片
try {
URL url = new URL("https://drive.google.com/...");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream stream = connection.getInputStream();
Bitmap teamBmpImage = BitmapFactory.decodeStream(stream);
teamImgView.setImageBitmap(teamBmpImage);
}
catch (Exception e) {
}
有人可以指导我做到这一点吗?
更新的代码:其中给出空指针异常
public class AboutActivity extends ActionBarActivity {
ImageView teamImgView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
teamImgView = (ImageView) this.findViewById(R.id.teamImageView);
new DownloadImageTask(teamImgView).execute("http://docs.oracle.com/javase/tutorial/2d/images/examples/strawberry.jpg");
}
class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//pd.show();
}
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;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//pd.dismiss();
bmImage.setImageBitmap(result);
}
}
}
[最佳方法从Android下载图片的最佳方法]可能的重复(http://stackoverflow.com/questions/18210700/best-method-to-download-image-from-url-in-android) – Lamorak
否解决方案从这个链接出来,这就是为什么创建新的问题 – Stella
实际上有几个好的技巧在答案中,如果你尝试了那些你应该在你的问题中提及它并指定出了什么问题 – Lamorak