How can I use a view model, with sqlite and a broadcast receiver to update the UI?

677 views Asked by At

I have an application that is used for testing connectivity, it has a 20min alarm, and must contact a server with a unique code, and the server sends an sms with the same code to confirm. I have all the components working, but I don't know how to get the unique code to automatically update in the UI. The alarm writes each request into an sqlite DB, and I would like that to automatically update the UI using an observable.

My project is in Kotlin if that makes any difference.

Basically, I'm just not figuring out how to "observe" the sql database for changes or how to have the broadcast receiver and the activity use the same observable

1

There are 1 answers

0
Asitaka On

This answer is not complete yet:

In order to do what I wanted, I have so far implemented a shared prefs listener and use that to relay data between the broadcast receivers and the UI. I also implemented an observable object with the new libraries, but I needed to run the app on an older device, so the observable didn't work.

private val listener = SharedPreferences.OnSharedPreferenceChangeListener { prefs, key ->
    val value = prefs.getString(key, "")
    when(key) {
        "sms" -> smsStatus.text = value
    }
} 
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_smschecker)
    //setSupportActionBar(toolbar)
    getSharedPreferences("SMS_CHECKER", MODE_PRIVATE).registerOnSharedPreferenceChangeListener(listener)
}

then in the broadcast receiver:

val editor = context.getSharedPreferences("SMS_CHECKER", Context.MODE_PRIVATE).edit()
    editor.putString("sms", DateFormat.getDateTimeInstance().format(Date()))
    editor.apply()

Still working on the sqlite monitoring.