android预填充sqlite数据库

时间:2011-03-10 14:48:48

标签: android sqlite

我的应用程序中有一个sqlite数据库。我的应用程序不应将其作为空数据库发送,但在用户第一次使用该应用程序之前,需要创建某些记录。当然我可以有很多插入语句,但这似乎很奇怪。我想到http://vineetyadav.com/tutorials/11-adding-prefilled-sqlite-database-to-android-app.html之类的东西基本上可行,但这意味着我手动创建的数据库也需要所有内部表,如android_metadata。所以我要么知道内部表存在什么以及如何填充它们。或者另一种拥有预填充数据库的智能方法。有什么建议吗?

谢谢,A。

3 个答案:

答案 0 :(得分:3)

你可以从SD卡读取一个平面文件,每行有1个插入语句,并遍历该文件。

这是一个类似的例子,我在其中读取文件并将ContactItem添加到我的contact_list中:

public ArrayList<ContactItem> readInputFile(Context context, String filename) {
    String text = null;
    BufferedReader reader = null;
    ArrayList<ContactItem> contact_list = new ArrayList<ContactItem>();
    contact_list.clear();  // Clear any existing contacts when a new file is read
    try {
        reader = new BufferedReader(new FileReader(filename));
        // Repeat until EOF
        while (((text = reader.readLine()) != null)) {
            if (!(text.length() > 1024)) {  //  If we read more than 1k per line there's a problem with the input file format
                ContactItem c = new ContactItem(text);
                if (c.getIsValid()) {
                    //  We were able to parse a well formed phone number from the last line read
                    contact_list.add(c);
                }
            }
        }
    } catch (FileNotFoundException e) {
        Toast.makeText(context, R.string.error_fileNotFound, 1).show();
        e.printStackTrace();
    } catch (IOException e) {
        Toast.makeText(context, R.string.error_ioException, 1).show();
        e.printStackTrace();
    } finally { // EOFException (or other, but EOF is handled and most likely)
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            Toast.makeText(context, R.string.error_generalFailure, 1).show();
            e.printStackTrace();
        }
    }
    return contact_list;
}

答案 1 :(得分:2)

我将数据作为JSON存储在res / raw目录中。当应用程序第一次打开时,我使用了AsyncTask,读取了JSON文件(使用了GSON库)并用它填充了我的数据库。

我已经尝试了大约1000条记录,它对我有用。它仍然需要一些时间 - 在模拟器上大约需要15-30秒。

不确定这是否是最佳方式。

答案 2 :(得分:1)

就我个人而言,我刚刚做了插入语句,但我只有2个所以它对我来说似乎并不是最重要的。

如果您需要了解内部表,为什么不从应用程序中提取数据库并查看任何SQLite数据库资源管理器(我使用SQLite Database Browser)?

android_metadata在SQLite数据库浏览器中显示为由CREATE TABLE android_metadata(locale TEXT)创建。

可能会插入一个声明,以确保它的外观。

那么您可以轻松地重新创建并添加它吗?