Android:从网络URL加载图像

4
可能重复:

可能重复:
加载远程图像

我正在开发一个应用程序,其中有一个列表,每一行都有一个图像,

这个图像是从 web URL 加载的。

以下是我的代码

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

    <ImageView
            android:id="@+id/list_row_img"
            android:layout_width="200dp"
            android:layout_height="200dp"
            />

    <TextView
            android:id="@+id/list_row_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

</LinearLayout>

这是活动代码。
@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView img= (ImageView) findViewById(R.id.list_row_img);
    Bitmap bm = null;
    try {
         URL aURL = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
         URLConnection conn = aURL.openConnection();
         conn.connect();
         InputStream is = conn.getInputStream();
         BufferedInputStream bis = new BufferedInputStream(is);
         bm = BitmapFactory.decodeStream(bis);
         img.setImageBitmap(bm);
         bis.close();
         is.close();

         } catch (Exception e) {
            Log.v("EXCEPTION", "Error getting bitmap", e);
         }
}

当我运行时,设备上没有任何东西。只有一个灰色的屏幕,没有发生异常。
请注意,我在清单文件中添加了此权限。
<uses-permission android:name="android.permission.INTERNET" />

可以有人帮忙吗?
3个回答

10

尝试这个 你可以执行它通过

      new DownloadImageTask((ImageView)  im1).execute(url here);

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }


/*    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        showProgressDialog();
    }*/

    protected void onPostExecute(Bitmap result) {
        //pDlg.dismiss();
        bmImage.setImageBitmap(result);
    }}

@Rana Osama 你试过这段代码吗? - Athul Harikumar
还没有,但我现在会努力工作...非常感谢您的帮助 =) - Rana Osama
我用过了,它非常好用!谢谢。 - Ton
简短而优美的回答。非常感谢!正是我所需要的! - Tobias Reich

7

使用以下代码从URL下载图像并将图像显示到ImageView中,这将解决您的问题。

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class MainActivity extends Activity {

    ImageView mImgView1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);

        mImgView1 = (ImageView) findViewById(R.id.mImgView1);
        String url = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
        BitmapFactory.Options bmOptions;
        bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;
        Bitmap bm = loadBitmap(url, bmOptions);
        mImgView1.setImageBitmap(bm);
    }

    public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in, null, options);
            in.close();
        } catch (IOException e1) {
        }
        return bitmap;
    }

    private static InputStream OpenHttpConnection(String strURL)
            throws IOException {
        InputStream inputStream = null;
        URL url = new URL(strURL);
        URLConnection conn = url.openConnection();

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpConn.getInputStream();
            }
        } catch (Exception ex) {
        }
        return inputStream;
    }
}

谢谢您的帮助。我有一个问题。OpenHttpConnection(URL) 这一行有错误。我需要导入什么API或库吗? - Rana Osama
@RanaOsama 不需要任何 API 或库。 - Dipak Keshariya
@RanaOsama 首先清理你的项目,然后再次运行它。 - Dipak Keshariya
4
虽然这个方法可行,但我建议你在从服务器下载时使用AsyncTask。绕过StrictMode.ThreadPolicy不是一个好主意。 - Lazy Ninja
对我来说没有用。 “很遗憾,应用程序关闭了” - Shahid Karimi
显示剩余3条评论

2

您的图片链接无效。尝试使用浏览器访问,您会发现这是您的问题。


1
+1 表示您已经查看链接。 - Gautam
@Gautam K @懒惰忍者 链接有效,加载了一张图片“尽管它被标记为无图像,但实际上是一张图片”。 - Athul Harikumar
链接有效。@Lazy,你遇到过任何问题吗? - Rana Osama
是的,有一个问题。请将URL更改为以下内容并检查:http://upload.wikimedia.org/wikipedia/commons/5/57/Galunggung.jpg - Lazy Ninja
你的链接也无法工作。我确定URL不是问题所在。当加载图像或获取URL内容时出现了一些问题。 - Rana Osama

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接