簡體   English   中英

使用Android應用程序捆綁SQLite數據庫

[英]Bundle SQLite Database with android app

我需要將一個靜態數據庫與我的Android應用程序捆綁在一起,每次安裝/更新應用程序時都必須將其替換。 我不希望在第一次活動的每個開始時都替換它。 將數據庫放在Assets中似乎不可行。 有什么方法可以使用AndroidStudio嗎?

您可以通過一些編碼來完成:

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

將數據庫放在Assets中似乎不可行

當然是啦。 使用SQLiteAssetHelper

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM