对于我的Android应用程序,我想使用一个大型数据库(大约45 MB)。
一种解决方案是将(拆分的)数据库包含在assets文件夹中,并在第一次启动时将其复制到数据库目录。
但是这会占用磁盘空间两次 - 一次在资产文件夹中,文件无法删除,一次在数据库目录中,它已被复制到。
所以我宁愿在第一次启动时从Internet(webserver)下载数据库。我怎么能这样做?我可以下载完整的SQLite文件并将其保存到数据库目录中吗?或者我应该使用用于填充数据库的JSON数据文件?
答案 0 :(得分:11)
一种解决方案是将(拆分的)数据库包含在assets文件夹中,并在第一次启动时将其复制到数据库目录。
它不必拆分,只是拉链。有关示例,请参阅SQLiteAssetHelper
。
我怎么能这样做?
使用HttpUrlConnection
。或者,使用HttpClient
。
我可以下载完整的SQLite文件并将其保存到数据库目录吗?
是。使用getDatabasePath()
获取正确的本地路径。
或者我应该使用用于填充数据库的JSON数据文件?
你可以,但对于45MB,这将是非常缓慢的。
答案 1 :(得分:7)
被问到我最终得到了什么解决方案,这是我使用的代码(大致)。它可能不再完整,也不优雅或干净。但也许这对你有帮助。
<强> MyActivity.java 强>
public class MyActivity extends Activity {
private static final String SD_CARD_FOLDER = "MyApp";
private static final String DB_DOWNLOAD_PATH = "http://www.example.org/downloads/dictionary.sqlite";
private Database mDB = null;
private DatabaseDownloadTask mDatabaseDownloadTask = null;
private DatabaseOpenTask mDatabaseOpenTask = null;
private class DatabaseDownloadTask extends AsyncTask<Context, Integer, Boolean> {
@Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(MyActivity.this);
mProgressDialog.setTitle(getString(R.string.please_wait));
mProgressDialog.setMessage(getString(R.string.downloading_database));
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
@Override
protected Boolean doInBackground(Context... params) {
try {
File dbDownloadPath = new File(Database.getDatabaseFolder());
if (!dbDownloadPath.exists()) {
dbDownloadPath.mkdirs();
}
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
HttpGet httpGet = new HttpGet(DB_DOWNLOAD_PATH);
InputStream content = null;
try {
HttpResponse execute = client.execute(httpGet);
if (execute.getStatusLine().getStatusCode() != 200) { return null; }
content = execute.getEntity().getContent();
long downloadSize = execute.getEntity().getContentLength();
FileOutputStream fos = new FileOutputStream(Database.getDatabaseFolder()+Database.DATABASE_NAME+".sqlite");
byte[] buffer = new byte[256];
int read;
long downloadedAlready = 0;
while ((read = content.read(buffer)) != -1) {
fos.write(buffer, 0, read);
downloadedAlready += read;
publishProgress((int) (downloadedAlready*100/downloadSize));
}
fos.flush();
fos.close();
content.close();
return true;
}
catch (Exception e) {
if (content != null) {
try {
content.close();
}
catch (IOException e1) {}
}
return false;
}
}
catch (Exception e) {
return false;
}
}
protected void onProgressUpdate(Integer... values) {
if (mProgressDialog != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.setProgress(values[0]);
}
}
}
@Override
protected void onPostExecute(Boolean result) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
if (result.equals(Boolean.TRUE)) {
Toast.makeText(MyActivity.this, getString(R.string.database_download_success), Toast.LENGTH_LONG).show();
mDatabaseOpenTask = new DatabaseOpenTask();
mDatabaseOpenTask.execute(new Context[] { MyActivity.this });
}
else {
Toast.makeText(getApplicationContext(), getString(R.string.database_download_fail), Toast.LENGTH_LONG).show();
finish();
}
}
}
private class DatabaseOpenTask extends AsyncTask<Context, Void, Database> {
@Override
protected Database doInBackground(Context ... ctx) {
try {
String externalBaseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
// DELETE OLD DATABASE ANFANG
File oldFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+SD_CARD_FOLDER);
File oldFile = new File(oldFolder, "dictionary.sqlite");
if (oldFile.exists()) {
oldFile.delete();
}
if (oldFolder.exists()) {
oldFolder.delete();
}
// DELETE OLD DATABASE ENDE
File newDB = new File(Database.getDatabaseFolder()+"dictionary.sqlite");
if (newDB.exists()) {
return new Database(ctx[0]);
}
else {
return null;
}
}
catch (Exception e) {
return null;
}
}
@Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this, getString(R.string.please_wait), "Loading the database! This may take some time ...", true);
}
@Override
protected void onPostExecute(Database newDB) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
if (newDB == null) {
mDB = null;
AlertDialog.Builder downloadDatabase = new AlertDialog.Builder(MyActivity.this);
downloadDatabase.setTitle(getString(R.string.downloadDatabase));
downloadDatabase.setCancelable(false);
downloadDatabase.setMessage(getString(R.string.wantToDownloadDatabaseNow));
downloadDatabase.setPositiveButton(getString(R.string.download), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mDatabaseDownloadTask = new DatabaseDownloadTask();
mDatabaseDownloadTask.execute();
}
});
downloadDatabase.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
downloadDatabase.show();
}
else {
mDB = newDB;
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mDatabaseDownloadTask != null) {
if (mDatabaseDownloadTask.getStatus() != AsyncTask.Status.FINISHED) {
mDatabaseDownloadTask.cancel(true);
}
}
if (mDatabaseOpenTask != null) {
if (mDatabaseOpenTask.getStatus() != AsyncTask.Status.FINISHED) {
mDatabaseOpenTask.cancel(true);
}
}
if (mProgressDialog != null) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
if (mDB != null) {
mDB.close();
mDB = null;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(getApplicationContext(), getString(R.string.sd_card_not_found), Toast.LENGTH_LONG).show();
finish();
}
mDatabaseOpenTask = new DatabaseOpenTask();
mDatabaseOpenTask.execute(new Context[] { this });
}
}
<强> Database.java 强>
public class Database扩展了SQLiteOpenHelper {
private static final String DATABASE_NAME = "dictionary";
private String DATABASE_PATH = null;
private static final int DATABASE_VERSION = 1;
private static final String PACKAGE_NAME = "com.my.package";
private SQLiteDatabase db;
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
DATABASE_PATH = getDatabaseFolder()+DATABASE_NAME+".sqlite";
db = getWritableDatabase();
}
public static String getDatabaseFolder() {
return Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data/"+PACKAGE_NAME+"/databases/";
}
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
try {
if (db != null) {
if (db.isOpen()) {
return db;
}
}
return SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}
catch (Exception e) {
return null;
}
}
@Override
public synchronized void close() {
if (db != null) {
db.close();
db = null;
}
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) { }
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}
答案 2 :(得分:3)
我认为如果您的数据库那么大,JSON方法会更好。
我不是100%肯定,但我相信当您发布应用程序更新时,您的设备将下载整个应用程序。如果您将45mb文件与应用程序捆绑在一起,这意味着每次推送更新时,您的用户将无法下载45mb文件。不是个好主意。
您可以做的是包含结构合理的数据库,而您的应用程序中没有数据。当用户打开应用程序时,它可以连接到您的Web服务器并获取JSON数据来填充数据库。这样,当用户更新您的应用程序时,他们不会因为下载新的大文件而陷入困境。更新不会消灭现有数据库。
您甚至可以通过JSON来获取并获取数据库的一部分,直到用户拥有所有内容。这样一来,如果你正在进行怪物查询并且他们失去了与互联网的连接,那么就不会发生太糟糕的事情。