Mark
Mark

Reputation: 41

Android overriding newView() and bindView() issue

Here's my custom simple cursor adapter:

public MySimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, 
        int[] to, int flags) {
    super(context, layout, c, from, to, 0);
    this.mContext = context;
    mInflater = LayoutInflater.from(context);
}

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

    return view;
}

@Override
public void bindView(View view, Context context, Cursor c) {

    TextView rowView = (TextView) view.findViewById(R.id.row);
    ImageView rowImg = (ImageView) view.findViewById(R.id.img);

    String img = null;
    String row = null;

    if (c != null) {
        img = c.getString(c.getColumnIndex(Db.TABLE_IMG));
        row = c.getString(c.getColumnIndex(Db.TABLE_TITLE));
    }

    if (img != null) rowImg.setImageResource(R.drawable.smiley);
    else img.setImageResource(0);

    rowView.setText(row);

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String[] from = new String[] { ... };
    int[] to = new int[] { ... };
            ... 
    getLoaderManager().initLoader(0, null, this);

    mAdapter = new MySimpleCursorAdapter(this, R.layout.row, null, from,
            to, 0);
    setListAdapter(mAdapter);


public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String[] projection = { Db.TABLE_ID,
            Db.TABLE_TITLE };

    CursorLoader c = new CursorLoader(this,
            MyProvider.CONTENT_URI, projection, null, null, null);
    return c;
}

public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    mAdapter.swapCursor(data);
}

public void onLoaderReset(Loader<Cursor> loader) {
    mAdapter.swapCursor(null);
}

Error when populating the ListView:

java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

Upvotes: 0

Views: 1804

Answers (1)

dymmeh
dymmeh

Reputation: 22306

Your projection { Db.TABLE_ID, Db.TABLE_TITLE } differs from the values you are trying to retrieve Db.TABLE_IMG and Db.TABLE_TITLE. Since you aren't querying for Db.TABLE_IMG when you try to access it through your adapter it will not exist (which throws the error). Change your projection to include Db.TABLE_IMG and that error should go away

Upvotes: 1

Related Questions