使用GreenDao加載assets下sqlite數(shù)據庫的示例

應用場景

已有的、某類型數(shù)據(如行政區(qū)域關系)保存在sqlite中,sqlite數(shù)據庫文件保存在assets目錄下,APP需要讀取該數(shù)據庫中的數(shù)據

工具

GreenDao3.2

實例

AndroidGreenDaoAssetsDbExample

要點介紹

  1. APP無法直接讀取assets中數(shù)據庫,必須將數(shù)據庫復制到APP的數(shù)據庫文件存儲目錄,這里注意需要判斷目標文件夾中如果已經存在同名的數(shù)據庫文件,則不再復制,避免重復執(zhí)行復制數(shù)據庫邏輯。
/**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     * */
    private void copyDataBase(String dbname) throws IOException {
        // Open your local db as the input stream
        InputStream myInput = this.getAssets().open(dbname);
        // Path to the just created empty db
        File outFileName = this.getDatabasePath(dbname);

        if (!outFileName.exists()) {
            outFileName.getParentFile().mkdirs();

            // Open the empty db as the output stream
            OutputStream myOutput = new FileOutputStream(outFileName);
            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            // Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
        }
    }

在Application的onCreate中,調用上述方法

        //復制assets目錄下的數(shù)據庫文件到應用數(shù)據庫中
        try {
            copyDataBase("zone.db");
        } catch (Exception e) {
            Log.e("Application", e.getMessage());
        }
  1. GreenDao的Entity一定要設置nameInDb,否則會讀不到數(shù)據
@Entity(
        nameInDb = "town",
        createInDb = false
)
public class Town {

    @Id
    @Property(nameInDb = "id")
    private Long id;

    @Property(nameInDb = "name")
    private String name;
    @Property(nameInDb = "code")
    private int code;
    @Generated(hash = 62109782)
    public Town(Long id, String name, int code) {
        this.id = id;
        this.name = name;
        this.code = code;
    }
    @Generated(hash = 2030923556)
    public Town() {
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getCode() {
        return this.code;
    }
    public void setCode(int code) {
        this.code = code;
    }

}

效果

數(shù)據庫結構
數(shù)據庫表中的數(shù)據
成功讀取數(shù)據庫中的數(shù)據
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容