Android Room, What will Query return if there isn't the matched row?

Viewed 568
@Dao
interface  ExampleDao {
    @Query("SELECT * FROM example_table WEHRE id = :id")
    fun getExample(id: Int): LiveData<Example>
}

What the above query returns if there is no matched id in the database? I guess it couldn't be null because the return type is non-nullable.

And does query return null if the return type is nullable? like LiveData<Example>? or LiveData<Example?>

1 Answers

I think you'll got a liveData object, but liveData.value gives you null.

and if you have an observer, it will receive a null no matter it's LiveData<Example> or LiveData<Example?>

for more details, you can see the yourDao_impl.java that Room generates for you.

and note that: it's not guaranteed to be non-null

  @Override
  public LiveData<Experiment> queryLiveData(final String profileId) {
    final String _sql = "SELECT * FROM experiment WHERE profileId= ?";
    return __db.getInvalidationTracker().createLiveData(new String[]{"experiment"}, false, new Callable<Experiment>() {
      @Override
      public Experiment call() throws Exception {
          ...
          final Experiment _result;
          if(_cursor.moveToFirst()) {
            _result = new Experiment();
            final String _tmpProfileId;
            _tmpProfileId = _cursor.getString(_cursorIndexOfProfileId);
          } else {
            _result = null;
          }
          return _result;
        } finally {
          _cursor.close();
        }
      }

and don't use LiveData<Example>? it seems not helping but gives you protential NPE.

Related