如何使用DAO从查询中检查值



我有一个有入门教程的应用程序,如果用户已经看过教程,我会保存在房间数据库中。为此,我在用户完成教程时保存数据,并在TutorialActivity的onCreateMethod中进行查询,以查看我是否跳到其他活动。我的DAO是两个方法,一个要插入,另一个要加载。我的加载方法(我想问的(有以下代码:

@Query("SELECT * FROM tutorial LIMIT 1")
    fun load(): Single<TutorialEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(userEntity: TutorialEntity): Single<Long>

我的实体:

@Entity(tableName = "tutorial")
class TutorialEntity (
    @PrimaryKey
    @ColumnInfo(name = "as_seen_tutorial")
    val asSeenTutorial: Long
)

这是我的教程活动:

注:我用dagger注射图torialDao(此处不重要(

//here is where I check if the value is already 1 to skip
    onCreate(){
    val load = tutorialDao.load()
    if(load.? contains 1) -> This is my doubt {      
      //OBJECTIVE: does not show and skips to other activity   
   } 
 }
//here is where I insert the flag into the database
fun showTutorial(){
  val entity = TutorialEntity(1)
  tutorialDao.insert(entity)
}

我想知道如何检查从选择查询中出现的值是否是一个

好吧。我不知道我是否理解你,但在回答你的疑问之前,我有一些问题。

你为什么使用单曲?(您将获得NPE((https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/single.html)

我建议您只使用类作为null,所以只需检查变量的

if (load?.asSeenTutorial == 1) {
   // Do your stuff
}

还要记住,您需要在AsyncTask下执行插入操作。

虽然您可以使用Room来完成此操作,但建议您最好不要使用Room进行此类操作。这些类型的单值检查是使用CCD_ 1来完成的。谷歌文档引用

如果要保存的键值集合相对较小,则应使用SharedPreferences API。

对于Room,您必须考虑创建@Entity@Dao,并在后台线程中调用它们。的工作量很大

以下是如何使用SharedPreference

val sharedPref = activity?.getSharedPreferences("AppPreference", Context.MODE_PRIVATE)

你检查下面的

if (sharedPref.getBoolean("as_seen_tutorial", false)){
    // show tutorial. 
    // false is a default value
}
else{
    // start another activity
}

展示完教程后,您将"as_seen_tutorial"保存为true,如下所示

with (sharedPref.edit()) {
    putBoolean("as_seen_tutorial", true)
    commit()
}

最新更新