When does Query return Null on Android?

I don't seem to find any information about the query, insert, or any other SQL method returning null. But this happens if an error occurs. I'm just wondering if the cursor is zero, means that an error has occurred, or could it mean that no rows were selected (for example)? I don’t know how I should relate to him - like a mistake or something that can happen from time to time.

+4
source share
3 answers

I do not believe that you need to check if(cursor == null) {} .

First
If your query does not return any rows, you will get an empty Cursor. The cursor will not be null .

There are many ways to check if the cursor is empty:

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

In fact, all cursor methods # moveTo ... () return either true or false , if you get false , then the line you requested does not exist.

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


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

+7
source

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 of the queries end:

 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 make sure that in the only case a local variable is not assigned to Cursor , a RuntimeException will be RuntimeException . The value of this function can never return null.

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

Note that SQLiteException can be SQLiteException later from SQLiteQuery when a nonzero Cursor read.

This specific Android source code has not been updated since 2012. He is stable πŸ‘

0
source

When the cursor displays non-selected rows, it returns (-1), if an error occurs, the cursor may be empty

-2
source

Source: https://habr.com/ru/post/1435577/


All Articles