Android调用Cursor.getColumnIndex报空对象引用错误如何解决?
问题原因
- 核心报错根因:
getContentResolver().query()方法在查询逻辑出错时会返回null,而非空的Cursor对象,你的代码未做非空校验就直接调用cursor.getColumnIndex()方法,触发空指针异常。 - 额外逻辑bug:你代码中获取firstName列索引的行写错了列名,
int idFirstName = cursor.getColumnIndex(MemberEntry.COLUMN_LAST_NAME);用了LAST_NAME的字段,后续即使查询成功也会出现数据显示错乱的问题。 - 潜在问题:Cursor资源未做安全关闭,若后续逻辑抛出异常会导致Cursor无法正常关闭,引发内存泄漏。
解决方案
第一步:修复displayData方法的非空判断与逻辑错误
修复后的代码如下:
private void displayData () { String [] projection = { MemberEntry._ID, MemberEntry.COLUMN_FIRST_NAME, MemberEntry.COLUMN_LAST_NAME, MemberEntry.COLUMN_GENDER, MemberEntry.COLUMN_SPORT }; Cursor cursor = null; try { cursor = getContentResolver().query( MemberEntry.CONTENT_URI, projection, null, null, null ); dataTextView.setText("All members\n\n"); dataTextView.append(MemberEntry._ID + " " + MemberEntry.COLUMN_FIRST_NAME + " " + MemberEntry.COLUMN_LAST_NAME + " " + MemberEntry.COLUMN_GENDER + " " + MemberEntry.COLUMN_SPORT + "\n"); // 先判断cursor非空再执行后续逻辑 if (cursor != null && cursor.getCount() > 0) { int idIndex = cursor.getColumnIndex(MemberEntry._ID); // 修复列名写错的问题 int idFirstName = cursor.getColumnIndex(MemberEntry.COLUMN_FIRST_NAME); int idLastName = cursor.getColumnIndex(MemberEntry.COLUMN_LAST_NAME); int idGender = cursor.getColumnIndex(MemberEntry.COLUMN_GENDER); int idSport = cursor.getColumnIndex(MemberEntry.COLUMN_SPORT); while (cursor.moveToNext()) { int currentID = cursor.getInt(idIndex); String currentFirstName = cursor.getString(idFirstName); String currentLastName = cursor.getString(idLastName); int currentGender = cursor.getInt(idGender); String currentSport = cursor.getString(idSport); dataTextView.append("\n" + currentID + " " + currentFirstName + " " + currentLastName + " " + currentGender + " " + currentSport); } } else { dataTextView.append("\n暂无成员数据"); } } finally { // 放在finally里保证cursor一定会被关闭 if (cursor != null) { cursor.close(); } } }
第二步:排查query返回null的原因
如果修改后还是提示暂无数据,说明你的ContentProvider查询逻辑有问题,优先检查以下几点:
- MemberEntry.CONTENT_URI是否和你ContentProvider中注册的URI匹配
- 数据库表是否正常创建,表字段和MemberEntry中定义的字段名是否完全一致
- ContentProvider的query方法是否正确实现,有没有异常没捕获导致返回null
内容的提问来源于stack exchange,提问作者777ILNITSKIY777
相关产品推荐
相关产品推荐

