CallousToTheEnd
CallousToTheEnd
2015-08-12 15:18

android中ImagView显示网络图片出错

  • android

初学就是想在ImageView上放一个网络图片,这代码哪里有问题,运行后会出错退出程序,在网上找了好多,但是代码我看着是一样的,为什么不行呢
activity代码:

 package com.lk.httptest;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {

    ImageView imageView;
    Bitmap bmige;
    String imgurl = "http://c.hiphotos.baidu.com/image/pic/item/8c1001e93901213f3a7182d556e736d12f2e957d.jpg";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setImageBitmap(returnBitmap(imgurl));
    }

    public Bitmap returnBitmap(String url){
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            URLConnection conn =  myFileUrl.openConnection();    
            conn.setDoInput(true);    
            conn.connect();    
            InputStream is = conn.getInputStream();    
            bitmap = BitmapFactory.decodeStream(is);    
            is.close();    

        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;

    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

XML布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView 
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />
</RelativeLayout> 

已经在manifest中添加了标签

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

6条回答

为你推荐