2

I've been chasing this bug for a few hours, and now that I've finally fixed it, I don't understand what caused it in the first place. I have a custom CursorAdapter with the following piece of code (full code posted at the end):

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    View view = mLayoutInflater.inflate(R.layout.xyz, parent, false);    // method 1
    // ...
}

The result:

empty rows

Turning on "Show layout bounds" in developer options and inspecting the layout via the Hierarchy Viewer both reveal that the rows are completely empty (no child views). Stepping through the code reveals that newView() and bindView() are called appropriately, layout inflation happens correctly (apparently), and data is correctly retrieved from the cursor and bound to the views in each row. Also the rows and their child views have their visibility flags set to VISIBLE and have non-zero dimensions. This leads me to conclude that my row layouts are not getting attached to the ListView, somehow.

It starts working as soon as I change it to:

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    View view = mLayoutInflater.inflate(R.layout.xyz, null);    // method 2
    // ...
}

This naturally prompted me to read the documentation on LayoutInflater.inflate() more thoroughly. As far as I understand, the first method should've worked just fine. And in fact method 2 should not be used because it causes the parent's LayoutParams to be completely ignored.

So my question is simply this: why doesn't method 1 work when it's supposed to be The Right Way™? Is it because there's something else wrong with my code (see below)?

private class XYZAdapter extends CursorAdapter {

    private LayoutInflater mLayoutInflater;

    public XYZAdapter(Context context, Cursor cursor, int flags) {
        super(context, cursor, flags);
        mLayoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @NotNull
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = mLayoutInflater.inflate(R.layout.xyz, parent, false);

        view.setTag(R.id.abc, view.findViewById(R.id.abc));
        // ... similarly cache references to all child views,
        // to avoid excessive calls to findViewById()

        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView abc = (TextView) view.getTag(R.id.abc);
        // ... extract all cached child view references

        abc.setText(cursor.getString(cursor.getColumnIndexOrThrow(XYZTable.COL_ABC)));
        // ... bind cursor data to views
    }

}
Vicky Chijwani
  • 10,191
  • 6
  • 56
  • 79

0 Answers0