應(yīng)用場(chǎng)景
已有的叮姑、某類型數(shù)據(jù)(如行政區(qū)域關(guān)系)保存在sqlite中,sqlite數(shù)據(jù)庫文件保存在assets目錄下肮雨,APP需要讀取該數(shù)據(jù)庫中的數(shù)據(jù)
工具
實(shí)例
AndroidGreenDaoAssetsDbExample
要點(diǎn)介紹
- APP無法直接讀取assets中數(shù)據(jù)庫渴析,必須將數(shù)據(jù)庫復(fù)制到APP的數(shù)據(jù)庫文件存儲(chǔ)目錄,這里注意需要判斷目標(biāo)文件夾中如果已經(jīng)存在同名的數(shù)據(jù)庫文件位隶,則不再復(fù)制拷窜,避免重復(fù)執(zhí)行復(fù)制數(shù)據(jù)庫邏輯。
/**
* 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中,調(diào)用上述方法
//復(fù)制assets目錄下的數(shù)據(jù)庫文件到應(yīng)用數(shù)據(jù)庫中
try {
copyDataBase("zone.db");
} catch (Exception e) {
Log.e("Application", e.getMessage());
}
- GreenDao的Entity一定要設(shè)置nameInDb篮昧,否則會(huì)讀不到數(shù)據(jù)
@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ù)據(jù)庫結(jié)構(gòu)
數(shù)據(jù)庫表中的數(shù)據(jù)
成功讀取數(shù)據(jù)庫中的數(shù)據(jù)