Hilmy S F
Hilmy S F

Reputation: 41

How to store data on Android Room Database without any button?

How to save data in Android Room Database without clicking any button? For example: on Samsung notes, we just need to write text on the title or body and notes are saved automatically without clicking any button on it. do I have to use one of the listeners?

Upvotes: 3

Views: 405

Answers (3)

Tong Jing Yen
Tong Jing Yen

Reputation: 219

If you want consistent autosave, you really should use RxJava or Kotlin Coroutines (even better) as Room fully supports them. You'll need to add either one of these dependencies:

implementation "androidx.room:room-ktx:$room_version"
implementation "androidx.room:room-rxjava2:$room_version"
implementation "androidx.room:room-rxjava3:$room_version"

Then, you can schedule your coroutine to save to Room for every 5 minutes or any interval you like.

P.S. For Kotlin Coroutines, use withContext(NonCancellable) to guarantee your data gets saved when your activity/application is destroyed.

Upvotes: 0

Geek Tanmoy
Geek Tanmoy

Reputation: 860

You can add TextChangeListener to the EditText and put logic of adding data to the afterTextChanged() method like this way.

binding.editText.addTextChangedListener(object :TextWatcher{

        var timer: CountDownTimer? = null
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable?) {
            timer?.cancel()
            timer = object : CountDownTimer(1000, 1500) {
                override fun onTick(millisUntilFinished: Long) {}
                override fun onFinish() {
                    //Put your data storing code here
                }
            }.start()
        }
    })

And you can change time interval as per your requirement.

Upvotes: 2

hamid Mahmoodi
hamid Mahmoodi

Reputation: 718

You can save data in onDestroy() of your view, or add a textChangeListener and update your DB here (Not recommended!)

Upvotes: 0

Related Questions