When Does Query Returns Null on Android?

♀尐吖头ヾ 提交于 2019-12-05 12:58:35

I don't believe you ever need to check if(cursor == null) {}.

First
If your query doesn't return any rows, you will receive an empty Cursor. The Cursor will not be null.

There are many ways to check if a Cursor is empty:

  • if(cursor.getCount == 0) {}
  • if(!cursor.moveToFirst()) {}

In fact all of the Cursor#moveTo...() methods return either true or false, if you receive false then the row that you requested does not exist.

Second
If an error occurs then you need to catch the error in a try-catch block, otherwise the app will crash from an unhandled exception.


Also insert(), update(), and delete() return an integer, not a Cursor. These methods return the number of rows affected by your statement, if no rows are affected these methods return 0.

If we look at the Android source code, from https://github.com/android/platform_frameworks_base/blob/master/core/java/android/database/sqlite/SQLiteDirectCursorDriver.java, where most queries end up:

public Cursor query(CursorFactory factory, String[] selectionArgs) {
    final SQLiteQuery query = new SQLiteQuery(mDatabase, mSql, mCancellationSignal);
    final Cursor cursor;
    try {
        query.bindAllArgsAsStrings(selectionArgs);

        if (factory == null) {
            cursor = new SQLiteCursor(this, mEditTable, query);
        } else {
            cursor = factory.newCursor(mDatabase, this, mEditTable, query);
        }
    } catch (RuntimeException ex) {
        query.close();
        throw ex;
    }

    mQuery = query;
    return cursor;
}

You can easily see that in the only case the local variable for the Cursor is not assigned then a RuntimeException will be thrown instead. Meaning this function can not ever return null.

You can hypothetically get a RuntimeException from the factory if used. Looking at the constructors for SQLiteQuery and SQLiteCursor no exceptions appear to be thrown. You can get an IllegalArgumentException if your bindings are incorrect during query.bindAllArgsAsStrings(selectionArgs);

Note an SQLiteException can be thrown later from the SQLiteQuery when the non-null Cursor is read.

That specific Android source code hasn't been updated since 2012. It is stable 👍

When a cursor results in no rows selected it returns (-1), if an error occurred the cursor can be null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!