简体   繁体   English

使用try / catch声明并初始化最终变量

[英]Using try/catch to declare and initialize a final variable

I'm trying to declare and initialize a final variable in an adapter in order to use the variable in an OnLongClickListener() declaration. 我正在尝试声明并初始化适配器中的最终变量,以便在OnLongClickListener()声明中使用该变量。 The problem is that the variable is being initialized by a method that can potentially throw a failure exception, so the initialization must happen in the context of a try/catch. 问题是变量正在被一个可能引发失败异常的方法初始化,因此初始化必须在try / catch的上下文中进行。 In the exception block, there is a fallback value that the final variable is assigned to instead. 在异常块中,有一个回退值,而是指定最终变量。 This all happens within the overridden getView() of the ArrayAdapter<T> . 这一切都发生在ArrayAdapter<T>的重写getView()中。

My question is, is there a slick way to do this? 我的问题是,有没有一个光滑的方式来做到这一点? I've gotten around this by just declaring a temporary variable outside the try/catch, and initializing it in the try/catch, then declaring and initializing the final variable after the try/catch block with the results of the temporary variable. 我通过在try / catch之外声明一个临时变量,并在try / catch中初始化它,然后在try / catch块之后使用临时变量的结果声明并初始化最终变量来解决这个问题。 This just feels too messy. 这只是感觉太乱了。

This question is pretty closely related, but the solution presented seems extreme. 这个问题非常密切相关,但提出的解决方案似乎极端。 Is it typical to wrap the entire contents of a method in a try/catch? 是否通常将方法的全部内容包装在try / catch中?

Code: 码:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) Data.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

//begin eww gross
        Vehicle temp;
        try {
            temp = Data.getVehicle(values.get(position).getId());
        } catch (ObjectNotFoundException e) {
            Log.e(TAG, e.getMessage() + "-- unable to find vehicle while getting list item vehicle for vehicles tab fragment");
            temp = values.get(position);
        }
        final Vehicle vehicle = temp;
//end disappointing, ugly workaround

        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.vehicle_item_with_img, null);
            holder = new ViewHolder();
            holder.vehicleLabel = (TextView) convertView.findViewById(R.id.vehicle_label);
            holder.statusImage = (ImageView) convertView.findViewById(R.id.lmImageView);
            holder.sImage = (ImageView) convertView.findViewById(R.id.sImageView);
            holder.vehicleTag = vehicle.getId();
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        if (Data.isFollowingVehicle(vehicle)) {
            holder.sImage.setVisibility(View.VISIBLE);
        }
        else {
            holder.sImage.setVisibility(View.INVISIBLE);
        }

        holder.statusImage.setImageDrawable(vehicle.getListIcon());
        holder.vehicleLabel.setText(vehicle.getFormattedLabel());

        final ViewHolder finalHolder = holder;
        convertView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (!vehicle.isFollowed()) {
                    finalHolder.sImage.setVisibility(View.VISIBLE);
                    mapInterface.follow(vehicle);
                } else {
                    finalHolder.sImage.setVisibility(View.GONE);
                    mapInterface.unfollow(vehicle);
                }
                return false;
            }
        });

        convertView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mapInterface.handleVehicleClickFromList(vehicle);
            }
        });

        return convertView;
    }

It is fine to move the logic to get the Vehicle into its own method. 可以移动逻辑以使Vehicle进入自己的方法。 It makes it reusable and easier to read. 它使它可重复使用,更易于阅读。

private Vehicle getVehicle(int position) {
    try {
        return Data.getVehicle(values.get(position).getId());
    } catch (ObjectNotFoundException e) {
        Log.e(TAG, e.getMessage() + "-- unable to find vehicle while getting list item vehicle for vehicles tab fragment");
        return values.get(position);
    }
}

and then back in your original method: 然后回到原来的方法:

final Vehicle vehicle = getVehicle(position);

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

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