2017-06-13 72 views
1

我需要绑定一个静态数据库与我的Android应用程序,必须在每次安装/更新应用程序时进行更换。我不希望它在第一次活动的每一次开始时都被替换。将数据库放置在资产中似乎不可行。有什么办法可以使用AndroidStudio来做到这一点?捆绑SQLite数据库与Android应用程序

回答

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(); 
} 
0

放置在资产数据库似乎并不可行当然

它。 Use SQLiteAssetHelper

+0

自述文件建议在build.gardle中添加一行,有两个build.gardle文件,一个用于项目,另一个用于模块。哪一个应该更新。据我猜测,它应该是项目之一。这是对的吗? –

+0

@VipulKumar:“哪一个应该更新” - 运行时依赖关系,比如'SQLiteAssetHelper'库,进入模块的'build.gradle'文件。 Gradle插件进入项目的'build.gradle'文件。 – CommonsWare

相关问题