将listview项目背景图像设置为从Web下载的drawable

时间:2014-06-22 03:07:28

标签: java android listview

我从网上下载图片并尝试将其设置为ListView适配器中充气列表元素的背景。这是我的方法(来自扩展BaseAdapter的类:

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    //working with an object called "hl"
    if (view == null){
        view = myInflater.inflate(R.layout.list_element, null);
    }

    Bitmap background = hl.getBgImage();
    Drawable dr = new BitmapDrawable(background);
    RelativeLayout rl = (RelativeLayout) view.findViewById(R.layout.headline_list);
    rl.setBackgroundDrawable(dr);
    return view;
}

但是,我在rl.setBackgroundDrawable(dr);行上收到NullPointerException。我添加图片的方式有问题吗?获取位图的方法如下,从不调用堆栈跟踪,所以我假设它正在正确下载?

private static Bitmap getBitmapFromURL(String imageUrl) {
    try {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

感谢您的任何建议。

编辑:我正在调用getBitmapFromUrl(String imageURL)

    String image = "http://www.google.com/trends/resources/2327917647-google-icon.png";
    Bitmap bg = getBitmapFromURL(image);
    Object hl = new Object(title, bg);
    objectList.add(hl);

2 个答案:

答案 0 :(得分:0)

发现了这个问题。应该完全忽略了relativelayout。

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    //working with an object called "hl"
    if (view == null){
        view = myInflater.inflate(R.layout.headline_list, null);
    }

    Bitmap background = hl.getBgImage();
    Drawable dr = new BitmapDrawable(background);
    view.setBackgroundDrawable(dr);
    return view;
}

答案 1 :(得分:0)

据我所知,代码行" rl.setBackgroundDrawable(dr);"除非rl为null,否则永远不会抛出NullPointerException,即使dr为null。所以请更新您的xml文件R.layout.list_element并让我们一起找到问题。 祝你好运!