android sqlite assets,使用GreenDao加载assets下sqlite数据库的示例

应用场景

已有的、某类型数据(如行政区域关系)保存在sqlite中,sqlite数据库文件保存在assets目录下,APP需要读取该数据库中的数据

工具

实例

要点介绍

APP无法直接读取assets中数据库,必须将数据库复制到APP的数据库文件存储目录,这里注意需要判断目标文件夹中如果已经存在同名的数据库文件,则不再复制,避免重复执行复制数据库逻辑。

/**

* 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目录下的数据库文件到应用数据库中

try {

copyDataBase("zone.db");

} catch (Exception e) {

Log.e("Application", e.getMessage());

}

GreenDao的Entity一定要设置nameInDb,否则会读不到数据

@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;

}

}

效果

9cc0870620c1

数据库结构

9cc0870620c1

数据库表中的数据

9cc0870620c1

成功读取数据库中的数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值