android - Safely insert data on SQLite database -
i need load data coming service in table on splashscreenactivity. i've followed this tutorial , works fine. have added custom asynctask run insert loop in background.
the problem if configuration change happens in middle of insert (e.g. screen rotation) blows , corrupted data saved on database.
i've read stuff cursorloader that's querying database. i've looked @ contentproviders don't solve problem.
any ideas on how handle problem?
what need is:
- access database background thread keep ui responsive.
- handle configuration changes when doing inserts on database.
update:
public class splashscreenactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_splash_screen); ... // create volley request , fetch data }
when response object start asynctask:
new response.listener<jsonobject>() { @override public void onresponse(jsonobject response) { if (response.optstring("lastrunstatus").equals( "success")) { jsonobject results = response .optjsonobject("results"); jsonarray objects = results .optjsonarray("objects"); new handleresponseasynctask().execute(objects); } }
in asynttask, insert objects:
private class handleresponseasynctask extends asynctask<jsonarray, string, void> { @override protected void onpreexecute() { mdatasource.open(); } @override protected void doinbackground(jsonarray... params) { publishprogress("deleting data..."); mproductosdatasource.deleteall(); publishprogress("saving data..."); jsonarray objects = params[0]; (int = 0; < objects.length(); i++) { jsonobject object = objects.optjsonobject(i); // each column value json ... mdatasource.insert(id, name, description); } return null; } @override protected void onprogressupdate(string... messages) { mtextviewloading.settext(messages[0]); } @override protected void onpostexecute(void result) { mdatasource.close(); // go main startmainactivity(); } }
note: mdatasource holds instance of helper class calls methods in custom sqliteopenhelper class.
Comments
Post a Comment