In android List Adapter, what if the convertView is null and not null ?Can anyone please explain for the below getView method

StackOverflow https://stackoverflow.com/questions/19543617

Question

What is the all about if(converView==null) { } else { } What if i avoid writing else part and how it effects my code ? I just wanted to know if it works fine without else part . Could someone explain about the gettag and settag for convertview???

            public View getView(int position, View convertView, ViewGroup parent) {
        DeviceViewHolder holder = null;
        mSelectedDeviceBin = getItem(position);

        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.single_device_view, null);
            holder = new DeviceViewHolder();
            holder.deviceId = (TextView) convertView
                    .findViewById(R.id.deviceId);

            holder.deviceType = (TextView) convertView
                    .findViewById(R.id.deviceType);

            convertView.setTag(holder);

        } else

            holder = (DeviceViewHolder) convertView.getTag();

        // Populating the views
        holder.deviceId.setText(mSelectedDeviceBin.getDeviceBinId());

        StringBuilder deviceCount = new StringBuilder();
        deviceCount.append("");
        double count = mSelectedDeviceBin.getQtyStock();
        deviceCount.append(count);
        String deviceCountString = deviceCount.toString();
        holder.deviceType.setText("Total number of Items:"
                + deviceCountString);

        return convertView;
    }
Was it helpful?

Solution

The implementation uses convertViews and the ViewHolder pattern, and works as follows.

Instead of inflating a new view for each item in your list, Android only creates so many views as are visible. Once a view goes out of screen, it will be reused. This way, the number of inflate calls, which are relatively slow, are minimized.

Secondly, the ViewHolder pattern makes sure the number of view finds (findViewById() ) are minimized, because this is relatively slow as well, especially when scrolling. So instead of finding the views every time, direct references are kept in memory, and stored in the ViewHolder. To make sure the correct ViewHolder object is stored with the correct item view, they are set inside the convertView with view.setTag(). They can be obtained by using the getTag() call.

The else is required, because otherwise the viewHolder variable would be null, and the app would crash.

For clarity I would advice you to write the else like this:

} else {
    holder = (DeviceViewHolder) convertView.getTag();
}

Edit: also, you can move the creation of the LayoutInflator inside the if(convertView == null){} statement. It is not needed otherwise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top