启动时不是空的LiteSQL DB

时间:2011-09-21 07:40:53

标签: android sqlite

我认为这是一个相当容易的问题。我已经太过年轻了。我想准备将使用数据库的应用程序。在我展示的每个例子中,都有一个空数据库,首先启动应用程序,之后有一些插入。我希望应用程序具有相当大的数据库,所以我想在应用程序启动时填充数据库。如何准备数据库并将其附加到程序?

1 个答案:

答案 0 :(得分:2)

  1. 将填好的数据库放入Package的资产目录

  2. 在应用程序运行时只需将该数据库复制到应用程序的内部存储器即可 data/data/<package name>/database目录。

  3. 然后使用它。
  4. 编辑:这是从资产目录到数据库目录的复制数据库,

    private void copyDataBase() throws IOException {
    
            try {
                // Open your local db as the input stream
                InputStream myInput = myContext.getAssets().open("your Database file name");
    
                // Path to the just created empty db
                String outFileName = "/data/data/<package name>/databases/";
                OutputStream myOutput = new FileOutputStream(outFileName);
    
                // transfer bytes from the inputfile to the outputfile
                byte[] buffer = new byte[1024];
                int length;
                while ((length = myInput.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }
    
                // Close the streams
                myOutput.flush();
                myOutput.close();
                myInput.close();
    
            } catch (Exception e) {
    
                Log.e("error", e.toString());
    
            }
    
        }