我需要将一个静态数据库与我的Android应用程序捆绑在一起,每次安装/更新应用程序时都必须将其替换。我不希望在第一次活动的每个开始时都替换它。将数据库放在Assets中似乎不可行。有什么方法可以使用AndroidStudio吗?
答案 0 :(得分:1)
您可以通过一些编码来实现:
import java.io.*;
import android.content.Context;
import android.content.res.AssetManager;
...
String dbName = /* db name */
Context context = /* read android context from somewhere */
File dbFile = context.getDatabasePath( dbName );
// Test if DB file has been previously deployed.
if( !dbFile.exists() ) {
// Deploy the DB file.
AssetManager assets = context.getAssets();
// Open an input stream on the source db file in assets.
// (Production code will need try/catch/finally around this block)
InputStream in = assets.open("dbname.sqlite");
// Open an output stream on the target location.
OutputStream out = new FileOutputStream( dbFile );
// Copy the contents. (In actual code you would want to
// use a buffer).
int byte;
while( (byte = in.read()) != -1 ) {
out.write( byte );
}
in.close();
out.close();
}
答案 1 :(得分:1)
将数据库置于资产中似乎不可行
当然可以。 Use SQLiteAssetHelper