繁体   English   中英

如何在Android中显示Uri中的位图图像?

[英]How to show a Bitmap image from Uri in Android?

我想使用Google Static Map API,并下载我所在位置的位图图像,并以图像的形式显示在我的应用程序中,我编写了此代码,但是我的应用程序停止了,这是什么问题?

码:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    String URL = "http://maps.google.com/maps/api/staticmap?center=48.858235,2.294571&zoom=15&size=200x200&sensor=false";
    Bitmap bmp = null;
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(URL);

    InputStream in = null;
    try {
        in = httpclient.execute(request).getEntity().getContent();
         bmp = BitmapFactory.decodeStream(in);
        in.close();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ImageView vi=(ImageView)findViewById(R.id.salak);
    vi.setImageBitmap(bmp);


}

我只是在Oncreate()函数中编写了这部分代码,并在.xml文件中有一个ImageViewer来显示图像,但是我的程序无法正常工作,如何解决此问题?

就像JRowan在评论中说的那样,最有可能导致问题的原因是您试图在主线程上进行网络调用,这是不允许的。

请参阅: http : //developer.android.com/reference/android/os/NetworkOnMainThreadException.html

从Uri加载ImageView的最简单方法是使用Square的Picasso库,可以在这里找到:

http://square.github.io/picasso/

您已经下载并安装了一个,然后可以像这样加载ImageView:

Picasso.with(context).load(yourUrl).into(yourImageView);

如果在活动中运行,则可以仅使用this作为上下文。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM