我的Android应用中有一个图片视图,我必须从网址设置一个简单的图像。我尝试了以下代码,但它没有从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) {
}
有人可以指导我做到这一点吗?
更新的代码:哪个给出Nullpointer异常
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);
}
}
}
答案 0 :(得分:2)
我猜你正在MainThread上执行代码,导致android中的NetworkOnMainThreadException
。尝试执行代码异步,如下例所示
new AsyncTask<String, Integer, Bitmap>() {
@Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bm) {
ImageView teamImgView = (ImageView) findViewById(R.id.teamImageView);
teamImgView.setImageBitmap(bm);
}
}.execute("https://drive.google.com/uc?....");
答案 1 :(得分:1)
您可以使用Picasso library,here是有关如何执行此操作的详细教程。
这是非常简单的示例用法
Picasso.with(activityContext)
.load("https://drive.google.com/uc?....")
.placeholder(R.drawable.image_name)
.into(imageView);
答案 2 :(得分:0)
正如bojan所说,你可以使用Picasso库来处理Android上许多常见的图像加载陷阱。
Picasso.with(context).load("http://myurl/myImage.png").into(imageView);
无论如何,也要查看这个威胁:)
答案 3 :(得分:0)
请尝试以下链接: http://www.tutorialsbuzz.com/2014/11/android-volley-url-imageview.html
这将帮助您使用Volley库加载您的图像,它将在网络线程上执行所有网络工作并在主UI线程上设置您的图像。它还有LRUCache部分,如果你愿意,你可以跳过它。