I'm trying to declare and initialize a final variable in an adapter in order to use the variable in an OnLongClickListener()
declaration. 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. 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>
.
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. This just feels too messy.
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;
}