为什么我无法在Android平台上显示图像

时间:2013-05-09 05:57:27

标签: android gif

在网站http://218.93.33.59:85/map/zjmap/ibikegif.asp?flag=2&id=9上,我们可以获得名为ibikegif.gif的gif图片。但是我无法在我的Android手机上显示它。我的代码是这样的:

/**
    *@param url the imageURL.it references to 
    *"http://218.93.33.59:85/map/zjmap/ibikegif.asp?flag=2&id=9" here
    *
    **/
    public Bitmap returnBitMap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is); //Attention:bitmap is null     
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

我已经测试了这段代码,但它确实有用。这基本上是你用一个区别做的,我还明确地将请求方法设置为GET。

public class MyActivity extends Activity {

    private ImageView imageView;
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView = (ImageView) findViewById(R.id.imageView);
    }

    @Override
    protected void onResume() {
        super.onResume();
        new AsyncTask<Void, Void, Void>() {
            Bitmap bitmap;

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    bitmap = returnBitMap("http://218.93.33.59:85/map/zjmap/ibikegif.asp?flag=2&id=9");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                imageView.setImageBitmap(bitmap);
                imageView.invalidate();
            }

        }.execute();
    }

    public Bitmap returnBitMap(String url) throws IOException {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        InputStream is = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.connect();
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(is != null) {
            is.close();
        }
        return bitmap;
    }
}