Duchynko
11/22/2019, 1:00 PM@Entity(tableName = "students")
data class Student(
@PrimaryKey(autoGenerate = true)
val id: Int? = null,
var studentName: String,
val studentId: String,
var purchaseDate: String,
val comment: String
)
DAO
@Dao
interface StudentDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun upsert(student: List<Student>)
@Query("select * from students")
fun getStudents(): LiveData<List<Student>>
}
Repository methods for upserting and getting List of Students
private fun persistFetchedStudents(fetchedStudents: StudentsResponse) {
GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
Log.i("StudentRepositoryImpl", "Called from persistFetchedStudents: fetchedStudents.students.size = " + fetchedStudents.students.size)
studentsDao.upsert(fetchedStudents.students)
}
}
Log -> fetchedStudents.students.size = 140
private fun isFetchStudentNeeded(): Boolean {
Log.i("StudentRepositoryImpl", "Called from isFetchStudentNeeded: studentsDao.getStudents().value = " + studentsDao.getStudents().value)
return studentsDao.getStudents().value.isNullOrEmpty()
}
Log -> studentsDao.getStudents().value = null
Is there anything I'm doing wrong? I can't see any issue myself.
Thanks for any help 🙂Giorgos Neokleous
11/22/2019, 1:03 PMdino9
11/22/2019, 1:08 PMDuchynko
11/22/2019, 1:26 PMclass StudentSportApplication: Application(), KodeinAware {
override val kodein = Kodein.lazy {
import(androidXModule(this@StudentSportApplication))
bind() from singleton { StudentDatabase(instance()) }
bind() from singleton { instance<StudentDatabase>().studentDao() }
...
Duchynko
11/22/2019, 1:31 PM@Database(
entities = [Student::class],
version = 1
)
abstract class StudentDatabase : RoomDatabase() {
abstract fun studentDao(): StudentDao
companion object {
@Volatile private var instance: StudentDatabase? = null
private val LOCK = Any()
operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
instance ?: buildDatabase(context).also { instance = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext,
StudentDatabase::class.java, "students.db")
.build()
}
}
Duchynko
11/22/2019, 1:37 PM@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(students: List<Student>) : List<Long>
This is returning me list of IDsdino9
11/22/2019, 1:47 PMdao.getStudents().observe(this, new Observer<List<Student>>() {
@Override
public void onChanged(@Nullable List<Student> student) { }});
Duchynko
11/22/2019, 1:48 PMinit {
studentNetworkDataSource.downloadedStudents.observeForever { newStudents ->
Log.i("StudentRepositoryImpl", "Called from init method.")
persistFetchedStudents(newStudents)
}
}
dino9
11/22/2019, 1:50 PMDuchynko
11/22/2019, 3:59 PM