开发者社区> 问答> 正文

url.openStream()报错??报错

如下代码种的url.openStream()一执行就报错,访问网络的权限也已经给了,鼓捣半天办实在是不知道为什么,求大伙儿帮忙看下

protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	button = (Button) this.findViewById(R.id.btnGet);
	imageView = (ImageView)this.findViewById(R.id.imgView);
	button.setOnClickListener(new View.OnClickListener() {

	    @Override
	    public void onClick(View v) {
		String urlString = "http://x.limgs.cn/f2/c1/up201301/342a0432638526a1c79471d86f3d7192.jpg";
		try {
		    URL url = new URL(urlString);
		    InputStream inputStream = url.openStream();
		    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
		    imageView.setImageBitmap(bitmap);
		    inputStream.close();

		} catch (MalformedURLException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    }
	});
    }

异常是这个:

android.os.NetworkOnMainThreadException

展开
收起
爱吃鱼的程序员 2020-06-22 18:57:47 993 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    你在UI主线程执行了网络访问操作,把你的网络访问放入独立线程吧UI线程中不能做耗时操作的,建议你,采用thread+handler来读取图片并显示到Imageview上,当然你也可以用AsyncTask来读取。
    上面两位说的对的,可以外面写个方法,oncreate里面调方法就可以了,不过如果是4.0或以上版本的话,方法里面不可以直接连接网络的,网上有4.0或以上版本连接方法,复制过来就好了

    2020-06-22 18:58:04
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载