【问题标题】:Android load image from url and show imageviewAndroid从url加载图像并显示imageview
【发布时间】:2016-05-26 12:08:32
【问题描述】:

我尝试从 url 加载图像并显示 imageview。我编写的代码女巫可以下载图像并显示它。但现在我想下载 facebook 用户图像并显示它。我知道如何检查 facebook 用户图像“像这样 http://graph.facebook.com/userid /picture?width=80&height=80 当我运行程序时,我有 RuntimeException 这是我的来源

private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... urls) {
        Bitmap map = null;
        for (String url : urls) {
            map = downloadImage(url);
        }
        return map;
    }

    // Sets the Bitmap returned by doInBackground
    @Override
    protected void onPostExecute(Bitmap result) {
        user_img.setImageBitmap(result);
    }

    // Creates Bitmap from InputStream and returns it
    private Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;
    }

    // Makes HttpURLConnection and returns InputStream
    private InputStream getHttpConnection(String urlString)
            throws IOException {
        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return stream;
    }
}



new GetXMLTask().execute((new String[] { URL }));

如果我的网址是 http://mywebsite./pic.jpg,那么程序运行完美,但我想显示 facebook 用户图片

【问题讨论】:

  • 什么是 RuntimeException? http://graph.facebook.com/user id /picture?width=80&amp;height=80 将发回 302 重定向,因此您需要确保遵循该重定向。
  • RuntimeException: 执行doInBackground时出错
  • 我的猜测是 getHttpConnection 返回 null 因为 GET 请求返回 302 而不是 HTTP_OK
  • 什么是您选择的解决方案。我只有 facebook 用户图片有问题
  • 解决办法是你跟着重定向

标签: java android facebook android-asynctask


【解决方案1】:

您应该使用毕加索。 将依赖项添加到您的项目中。此外,只需一行代码即可完成任务。 Picasso.with(context).load("http://somepath/someimage.png").into(imageView); 无需编写线程和优化位图。

您可以参考:http://square.github.io/picasso/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2017-01-31
    • 2019-02-17
    • 1970-01-01
    • 2021-09-29
    相关资源
    最近更新 更多