如何在Android中的sqlite数据库中插入大量的数据 [英] How to insert large amount of data in sqlite database in Android

查看:662
本文介绍了如何在Android中的sqlite数据库中插入大量的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大量的数据存储在一个CSV文件(大约20,100行),我需要插入一个sqlite数据库。



需要很长时间才能完成。

解决方案

如你所建议,行数是巨大的,我建议不要使用 AsyncTask ,因为它不绑定到你的Activity生命周期,即如果你的活动开始它死了,它不表示 AsyncTask 因此,如果你尝试启动一个AsyncTask,并以某种方式如果你的活动死亡,例如屏幕旋转或回键按下,在重新启动另一个 AsyncTask 将得到spawned而不是链接已经执行 AsyncTask 。因此,我将推荐以下方法



(A)






  1. 创建 IntentService handleIntent api已经在工作线程中执行,所以你不必担心任何事情,一旦所有消息在其队列中完成,它会自动消失,所以不必担心泄漏任何资源。 / p>


  2. 写入大量插入行的逻辑,使用content resolver bulkInsert()api。


  3. 完成所有插入操作后,您可以执行回滚和错误检查,


所有这一切,你将实现两个主要的挑战


  1. 不挂断您的用户界面,转义任何可能的ANR

  2. 即使按下回车键,操作在后台任务中顺利进行。


I have a lot of data that is stored in a CSV file (about 20,100 rows), which I need to insert into a sqlite database.

This insert is taking very long to complete. What is the fastest way to insert this data?

解决方案

As you have suggested, number of rows are huge I will recommend not to use AsyncTask, as its not tied to your Activity lifecycle i.e if you activity which started it dies, it doesnt mean AsyncTask dies as well, so if you try initiate a AsyncTask and somehow if your activity dies e.g screen rotation or back key pressed, upon restarting another AsyncTask will get spawned rather then it getting linked to already executing AsyncTask. hence duplicating same operations.

So, all in all I would recommend following approach

(A)

  1. Create a IntentService, it's handleIntent() api already executes in a worker thread so you don't have to worry about any thing, and once all messaged in its queue are finished it automatically dies, so no worry at all about leaking any resources.

  2. write your logic for inserting rows in bulk, use content resolver bulkInsert() api for same. I will recommend inserting in 100 roes per batch, you can implement rollback and error checks to make sure insert goes normally.

  3. Once all insert is finish, you can post back to your UI using Handler and Messengers.

with all this you will achieve two major challenge

  1. Not to hang up your UI, escaping any possible ANR
  2. Even if back key is pressed, ensured that db operation goes on smoothly as it was taken up in background task.

这篇关于如何在Android中的sqlite数据库中插入大量的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆