[英]When should I save data into SQLite entered into a fragment in my Android app?
I was watching one of Google's app reviews and they were ripping into this guys' app who had a save button and if you didn't save before leaving it would pop up a dialog. 我正在观看谷歌的一个应用程序评论,他们正在抓住这个有保存按钮的人的应用程序,如果你在离开之前没有保存就会弹出一个对话框。 They said an android app should just save and not bother the user. 他们说Android应用程序应该保存而不是打扰用户。
I have a fragment and have several fields and need to determine when to save the data into a SQLite database. 我有一个片段,有几个字段,需要确定何时将数据保存到SQLite数据库。 I was thinking of saving on exit of each field via the onFocusChange
event? 我想通过onFocusChange
事件保存每个字段的退出? Or maybe that's too often? 或者也许这种情况经常发生? Perhaps the fragment's onPause
event? 也许片段的onPause
事件? When should I save (specific event please)? 我应该什么时候保存(具体事件请)?
Fragments
are much like the activities
when it comes to lifecycle. Fragments
非常类似于生命周期中的activities
。 So onPause()
is the right place to save persistent state, later after onPause()
it may be too late and can lead to data loss. 因此onPause()
是保存持久状态的正确位置,稍后在onPause()
它可能为时已晚并且可能导致数据丢失。 Google recommends to use "edit in place" user model. Google建议使用“就地编辑”用户模型。 That is, save edits immediately, in your case saving data when the user switches between input fields is good approach. 也就是说,在用户在输入字段之间切换时保存数据的情况下,立即保存编辑是一种很好的方法。 This prevents data loss if your Fragment
/ Activity
is killed by the system. 如果您的Fragment
/ Activity
被系统杀死,这可以防止数据丢失。 If you think it can take few seconds to save your state you can use also IntentService
in onPause()
. 如果您认为保存状态可能需要几秒钟,那么您也可以在onPause()
使用IntentService
。 In your scenario I would execute AsyncTask
updating your database when the user switches between input fields, maybe with detecting if change really occured. 在您的场景中,当用户在输入字段之间切换时,我会执行AsyncTask
更新数据库,可能会检测是否确实发生了更改。
Edit: If you are using ContentProvider
than consider using AsyncQueryHandler instead of AsyncTask
. 编辑:如果您使用的是ContentProvider
不是考虑使用AsyncQueryHandler而不是AsyncTask
。
public void onDestroy()
Called when the fragment is no longer in use. This is called after onStop() and before onDetach().
I would probably use that; 我可能会用那个; it would mean the user is done using that fragment. 这意味着用户完成了使用该片段。 I don't know of any cons in doing it that way or your way. 我不知道这样或那样做的任何缺点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.