1

我的应用程序附带了一个相当大的数据库。我在让它在本地设备上正确创建自己时遇到了很多麻烦,所以我认为问题和它是如此之大,将它托管在服务器上并从那里使用它可能更有意义。

数据库为 40 MB 或更少。将其托管在某处的最佳方法是什么?

4

1 回答 1

1

问题在于Database file尺寸。Zip您可以制作一个Database文件,然后将其复制到您的本地路径Assets

这是链接:从资产复制 Db 文件

现在,在该代码中将copyDataBase()函数替换为下面的函数。

private void copyDataBase() throws IOException {
    try {
       InputStream mInputStream = mContext.getAssets().open(DB_NAME_ZIP);
       String outFileName = DB_PATH + DB_NAME_ZIP;
       OutputStream mOutputStream = new FileOutputStream(outFileName);
       byte[] buffer = new byte[1024];
       int length;
       while ((length = mInputStream.read(buffer)) > 0) {
          mOutputStream.write(buffer, 0, length);
       }

       ZipFile mZipFile = new ZipFile(DB_PATH + DB_NAME_ZIP);
       InputStream nInputStream = mZipFile.getInputStream(mZipFile.getEntry(DB_NAME));
       OutputStream nOutputStream = new FileOutputStream(DB_PATH + DB_NAME);
       while ((length = nInputStream.read(buffer)) > 0) {
          nOutputStream.write(buffer, 0, length);
       }
       nOutputStream.flush();
       nOutputStream.close();
       nInputStream.close();

       // Close the streams
       mOutputStream.flush();
       mOutputStream.close();
       mInputStream.close();
    } catch (Exception e) {
       e.printStackTrace();
    } finally {
       //Delete Zip file to minimize memory usage
       final String mPath = DB_PATH + DB_NAME_ZIP;
       final File file = new File(mPath);
       if (file.exists())
          file.delete();
    }
}
  • DB_NAME_ZIPDatabase Zip您放在Assets文件夹中的文件,Android.zip但它实际上包含Android.sqliteor Android.db

我希望这个可以帮助你。

于 2013-05-02T03:45:39.180 回答