Search code examples
androidandroid-listviewandroid-arrayadapter

getView() Called multiple times for same position


I'm trying to load Array of files detail to ListView... Here my files array returns me 1 record from DB. And i'm loading this array into my custom arrayAdapter..

Issue:

CustomArrayAdapter getView() method calls 3 time for 0th position

1st time convertView will be null

2nd time convertView is not null

3rd time convertView is null again

Here is my code,

ArrayList files = null;

            try {
                files = db.getRecords(tableName, null, Type LIKE '.txt' , null, null, null, null);
            } catch (Exception e) {
                e.printStackTrace();
            }

            /*** files.size() = 1 ***/

            infoAdt = new InfoAdapter(mContext, R.layout.custome_view, files);
            setListAdapter(infoAdt);

            public class InfoAdapter extends ArrayAdapter<Object>  {

        public InfoAdapter(Context context, int textViewResourceId, List<Object> objects) {
            super(context, textViewResourceId,objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

             if (convertView == null) {      

                 LayoutInflater inf = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                 convertView = inf.inflate (R.layout.custome_view, parent, false);      

                 ViewHolder viewHolder = new ViewHolder();
                 viewHolder.nameView = (TextView) convertView.findViewById(R.id.name);
                 viewHolder.typeView = (TextView) convertView.findViewById(R.id.type);
                 viewHolder.sizeView = (TextView) convertView.findViewById(R.id.size);

                 convertView.setTag(viewHolder);
             }

             ViewHolder holder = (ViewHolder) convertView.getTag();

            FileItem f = (FileItem) getItem(position);          

            String[] fileNameAndType= f.getFileName().split("\\.");

            holder.nameView.setText(fileNameAndType[0]);
            holder.typeView.setText(fileNameAndType[1]);

            return convertView;
        }
    }

    class ViewHolder{
        TextView nameView;
        TextView typeView;
        TextView sizeView;
    }

Solution

  • It's normal that the index 0 view is requested multiple times. It is needed for measure/layout purposes.

    You can put a debugger breakpoint in getView() to learn why the adapter getView() was called in each case by observing the call stack.

    Make sure your ListView is not in a layout that requires multiple measure/layout passes, such as LinearLayout with weights or RelativeLayout with complex constraints.

    Make your getView() return a view as quickly as possible for performance reasons.