【问题标题】:Android Room, What will Query return if there isn't the matched row?Android Room,如果没有匹配的行,Query 会返回什么?
【发布时间】:2020-03-04 02:10:31
【问题描述】:
@Dao
interface  ExampleDao {
    @Query("SELECT * FROM example_table WEHRE id = :id")
    fun getExample(id: Int): LiveData<Example>
}

如果数据库中没有匹配的id,上面的查询会返回什么?我猜它不能为空,因为返回类型不可为空。

如果返回类型可以为空,查询是否返回空?喜欢LiveData&lt;Example&gt;?LiveData&lt;Example?&gt;

【问题讨论】:

    标签: android android-room android-architecture-components android-jetpack


    【解决方案1】:

    我想你会得到一个 liveData 对象,但 liveData.value 给你 null。

    如果你有一个观察者,无论是LiveData&lt;Example&gt; 还是LiveData&lt;Example?&gt;,它都会收到null

    更多详情,您可以查看 Room 为您生成的yourDao_impl.java

    并注意:不保证不为空

      @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();
            }
          }
    

    并且不要使用LiveData&lt;Example&gt;?,它似乎没有帮助,但会给你潜在的 NPE。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 2011-02-04
      相关资源
      最近更新 更多