Reputation: 5047
I have this app that has a start tutorial and I am saving in room database if the user already saw the tutorial. For that I save the data when the user finishes the tutorial and do a query in the onCreateMethod of the TutorialActivity to see if I skip to other activity. My DAO as two methods, one to insert and another to load. My load method(what I want to ask) has the following code:
@Query("SELECT * FROM tutorial LIMIT 1")
fun load(): Single<TutorialEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(userEntity: TutorialEntity): Single<Long>
My entity:
@Entity(tableName = "tutorial")
class TutorialEntity (
@PrimaryKey
@ColumnInfo(name = "as_seen_tutorial")
val asSeenTutorial: Long
)
This is my tutorial activity:
Note: I use dagger to inject the tutorialDao(not important here)
//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)
}
I wanted to know how can I check if the value that cames from the select query is one
Upvotes: 0
Views: 244
Reputation: 6882
While you can do this using Room, it is suggested that you better not use Room for such operations. These kinds of single value checks are done using SharedPreference
.
Quoted by Google Documentation
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs.
With Room you have to consider creating @Entity
, @Dao
, call them in background thread. which are so much work
Here is how you do it with SharedPreference
val sharedPref = activity?.getSharedPreferences("AppPreference", Context.MODE_PRIVATE)
And you check it as below
if (sharedPref.getBoolean("as_seen_tutorial", false)){
// show tutorial.
// false is a default value
}
else{
// start another activity
}
And after showing your tutorial, you save "as_seen_tutorial" as true
like below
with (sharedPref.edit()) {
putBoolean("as_seen_tutorial", true)
commit()
}
Upvotes: 1
Reputation: 467
Well. I don't know if i understand you well but i had some questions before respond your doubt.
Why are you using a Single? (You are going to receive a NPE) (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/single.html)
I recommend you to use just the class as nullable, so just check your variable for
if (load?.asSeenTutorial == 1) {
// Do your stuff
}
And also remember that you need to do the insert operation under an AsyncTask.
Upvotes: 1