應用場景
已有的、某類型數(shù)據(如行政區(qū)域關系)保存在sqlite中,sqlite數(shù)據庫文件保存在assets目錄下,APP需要讀取該數(shù)據庫中的數(shù)據
工具
實例
AndroidGreenDaoAssetsDbExample
要點介紹
- 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());
}
- 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ù)據