最近在研究Android 从网络上获取图片 总是报错 求大神解答
我的源码StringimageUrl="http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Hukou_Wa...
我的源码
String imageUrl = "http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Hukou_Waterfall.jpg/800px-Hukou_Waterfall.jpg";
ImageView imView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imView = (ImageView) findViewById(R.id.image);
imView.setImageBitmap(getHttpBitmap(imageUrl));
}
public static Bitmap getHttpBitmap(String url){//获取到图片
URL myFileURL;
Bitmap bitmap=null;
try{
myFileURL = new URL(url);
HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();//获得连接
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true); //连接设置获得数据流
conn.setUseCaches(true); //使用缓存
conn.connect();
InputStream is = conn.getInputStream(); //得到数据流
bitmap = BitmapFactory.decodeStream(is);//解析得到图片
is.close(); //关闭数据流
}catch(Exception e){
}
return bitmap;
} 展开
String imageUrl = "http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Hukou_Waterfall.jpg/800px-Hukou_Waterfall.jpg";
ImageView imView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imView = (ImageView) findViewById(R.id.image);
imView.setImageBitmap(getHttpBitmap(imageUrl));
}
public static Bitmap getHttpBitmap(String url){//获取到图片
URL myFileURL;
Bitmap bitmap=null;
try{
myFileURL = new URL(url);
HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();//获得连接
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true); //连接设置获得数据流
conn.setUseCaches(true); //使用缓存
conn.connect();
InputStream is = conn.getInputStream(); //得到数据流
bitmap = BitmapFactory.decodeStream(is);//解析得到图片
is.close(); //关闭数据流
}catch(Exception e){
}
return bitmap;
} 展开
2个回答
展开全部
Bitmap bitmap;
Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
imView.setImageBitmap(bitmap);
};
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imView = (ImageView) findViewById(R.id.image);
new Thread(new Runable(){
@Override
public void run(){
bitmap=getHttpBitmap(imageUrl);
handler.sendEmptyMessage(0);
}
}).start();
}
这样写试试
Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
imView.setImageBitmap(bitmap);
};
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imView = (ImageView) findViewById(R.id.image);
new Thread(new Runable(){
@Override
public void run(){
bitmap=getHttpBitmap(imageUrl);
handler.sendEmptyMessage(0);
}
}).start();
}
这样写试试
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询