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

谢谢。

最佳答案

您可以从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;
}

关于android pre-fill sqlite数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5261372/

10-11 22:16
查看更多