我在我的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