简体   繁体   English

对象引用的错误转换:未经检查/未经确认的转换

[英]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: Android Studio 的 Findbugs 插件抱怨 getview 方法的第一行,它说:

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. Unchecked/unconfirmed cast 此转换是未检查的,并非所有类型的实例都可以转换为它正在转换的类型。 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.如果你想取悦 FindBugs,你可以断言 convertView 是一个 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 .并非每个View都是ImageView ,因此 FindBugs 试图警告您强制转换可能会导致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.但是,您实际上无法获得ClassCastException因为convertView工作方式是您要么接收null ,要么接收先前由getView()方法返回的View Since your method always returns an ImageView , everything is fine.由于您的方法总是返回一个ImageView ,所以一切都很好。

FindBugs finds potential problems with your code, and sometimes they are actually not problems at all. FindBugs 会发现您的代码的潜在问题,有时它们实际上根本不是问题。

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:我认为您尝试用图像填充 listView 或回收视图的每一行...首先您应该制作包含图像视图的布局,然后您可以通过以下方式进行:

@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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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