I'm fetching data from API I created and storing it in room database. I'm trying to display data stored in the room database when offline but it keeps destroying itself. Please help.
I want if there data in database but not internet to display in recycler view but play to show no network. If there no internet and no data in database to show not data in recyclerview
Checking whether there is internet
if (!isConnected){
program.text = "Requires internet"
//startTime.visibility = View.INVISIBLE
//endTime.visibility = View.INVISIBLE
// emptyString.visibility = View.VISIBLE
// emptyString.text = "No internet"
apiViewModel.programs.observe(this) {
programs -> run {
adapter.submitList(programs)
// Log.d("Programs", "$programs")
}
}
play.setOnClickListener {
Toast.makeText(this, "Requires internet", Toast.LENGTH_SHORT).show()
}
stop.setOnClickListener {
finish()
stopService(Intent(this, BackgroundStreamService::class.java))
}
} else{
//startTime.visibility = View.VISIBLE
//endTime.visibility = View.VISIBLE
play.setOnClickListener {
if(isPlaying){
play.setImageResource(R.drawable.baseline_play_arrow_24)
stopService(Intent(this, BackgroundStreamService::class.java))
isPlaying = false
}else{
startForegroundService(Intent(this, BackgroundStreamService::class.java))
isPlaying = true
//play.setBackgroundResource(R.drawable.baseline_stop_24)
play.setImageResource(R.drawable.baseline_stop_24)
}
}
stop.setOnClickListener {
finish()
stopService(Intent(this, BackgroundStreamService::class.java))
}
//fetchPrograms()
apiViewModel.programs.observe(this) {
programs -> run {
adapter.submitList(programs)
Log.d("Programs", "$programs")
}
}
}
Repo
val programs: LiveData<List<Program>> = Transformations.map(programDao.getPrograms()){
it.asDomainModel()
}
suspend fun refreshPrograms(){
withContext(Dispatchers.IO){
val programs = NodejsApi.programApi.getProgramAsync().await()
programDao.insertAll(programs)
}
}
Realized that I needed also to check whether there is data in database after checking that if the phone is connected to the internet.
if (programs.isEmpty()){
emptyString.visibility = View.VISIBLE
emptyString.text = "No data in the database. \nPlease turn on the internet."
}else{
adapter.submitList(programs)
}