2013-05-02 51 views
1

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

数据库为40 MB或更少。在什么地方管理它的最佳方式是什么?

+0

将其存储在SD卡中并使用[openDatabase](http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#openDatabase(java.lang.String,android.database.sqlite.SQLiteDatabase .CursorFactory,int))管理它? – tigger 2013-05-02 01:34:20

+0

我不太明白。我将数据库存储在资产中,之前我使用代码将其复制到用户的手机中。任何尝试将代码存储在SD卡中失败。有没有办法远程托管它? – muttley91 2013-05-02 03:23:24

+0

sqlite数据库文件是40MB,必须保存在资产文件夹中?如果是这样,这取决于你决定。如果您决定远程维护数据库,则可能需要使用其他数据库以及一些脚本语言,如servlet或php等。 – Kanth 2013-05-02 03:34:15

回答

1

问题出在Database file的大小。您可以制作Database文件的Zip,然后将其从Assets复制到您的本地路径。

这里是链接:Copy Db File From Assets

现在,在代码替换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.sqliteAndroid.db

我希望这个人能帮助你。

+0

我也需要适配器类吗?我从这个链接使用DataBaseHelper类时并不需要它:http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ 看起来很多额外的工作使用适配器。是否有可能使用您的方法与我使用的代码? – muttley91 2013-05-02 04:20:08

+0

@rar是可以在代码中使用我的方法,但请注意,因为我将两个类DatabaseHelper和DBAdpater之间的所有方法分开。 – 2013-05-04 04:22:54

+0

这会解决在设备上创建的问题,还是只能成功保持数据库的大小? – muttley91 2013-05-05 16:39:44