When should I save data in SQLite entered into a fragment in my Android application?

I watched one of the Google app reviews, and they copied the guy’s app that had a save button, and if you didn’t save it before leaving, a dialog will appear. They said the Android app should just save and not bother the user.

I have a fragment and several fields, and I need to determine when to save the data in the SQLite database. I was thinking about saving when exiting each field through the onFocusChange event? Or maybe it's too often? Perhaps a snippet of onPause event? When should I save (specific event)?

+4
source share
2 answers

Fragments very similar to activities when it comes to the life cycle. Thus, onPause() is the right place to maintain a constant state, later after onPause() may be too late and can lead to data loss. Google recommends using a custom "change in place" model. That is, immediately save the changes, in your case, saving data when the user switches between the input fields is a good approach. This prevents data loss if your Fragment / Activity system is killed by the system. If you think it might take a few seconds to save state, you can also use IntentService in onPause() . In your scenario, I would perform AsyncTask updating your database when the user switches between the input fields, possibly with the detection of whether the changes have actually occurred.

Edit: if you are using ContentProvider than consider AsyncQueryHandler instead of AsyncTask .

+3
source
 public void onDestroy() Called when the fragment is no longer in use. This is called after onStop() and before onDetach(). 

I would probably use this; this will mean that the user is executed using this fragment. I do not know any flaws in doing this anyway.

+1
source

All Articles