简体   繁体   中英

Bad casts of object references: unchecked/unconfirmed cast

Consider the code below:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView =  (ImageView) convertView; //here

        if (imageView == null) {
            imageView = (ImageView) inflater.inflate(R.layout.item_gallery_image, parent, false);
        }
        ImageLoader.getInstance().displayImage(IMAGE_URLS[position], imageView, options);
        return imageView;
    }

Findbugs plugin from Android Studio is complaining about the first line from the method getview, it says:

Unchecked/unconfirmed cast This cast is unchecked, and not all instances of the type casted from can be cast to the type it is being cast to. Check that your program logic ensures that this cast will not fail.

Any ideas of how do I resolve this issue?

If you want to please FindBugs you can assert that convertView is an ImageView.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.item_gallery_image, parent, false);
    }
    assert convertView instanceof ImageView : convertView;
    ImageLoader.getInstance().displayImage(IMAGE_URLS[position], (ImageView) imageView, options);
    return imageView;
}

Not every View is an ImageView , so FindBugs is trying to warn you that the cast may result in a ClassCastException .

However, you actually can't get a ClassCastException because the way convertView works is that you either recieve null or you receive a View previously returned by the getView() method. Since your method always returns an ImageView , everything is fine.

FindBugs finds potential problems with your code, and sometimes they are actually not problems at all.

i think you try to fill every row of a listView or recycle view with image...first you should make layout that contains an image view then you can do it in this way:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        view=inflater.inflate(R.layout.adapter_row,parent,false);
        ImageView mImage=(ImageView) view.findViewById(R.id.imageid);
        ImageLoader.getInstance().displayImage(IMAGE_URLS[position], mImage, options);
        return view;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM