应用场景
已有的、某类型数据(如行政区域关系)保存在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;
}
}
效果
数据库结构
数据库表中的数据
成功读取数据库中的数据