Android开发系列(十七):读取assets目录下的数据库文件 – 源码巴士
数据库文件不像 assets 目录下的 htm 和 图片 能直接使用,需要复制出来才能使用。
CatalogActivity.java
String filename_db = "laws.db";
String path_db = getFilesDir().getPath() + File.separator + filename_db;
void copyDB() {
try {
InputStream IS = getAssets().open(filename_db);
FileOutputStream FOS = new FileOutputStream(path_db);
byte[] buffer = new byte[1024];
int count;
while ((count = IS.read(buffer)) > 0) {
FOS.write(buffer, 0, count);
}
FOS.flush();
FOS.close();
IS.close();
} catch (Exception e) {
Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
copyDB();
DBHelper helper = new DBHelper(this);
Cursor cursor = helper.catalog(s);
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
static String DATABASE_NAME = CatalogActivity.path_db;
static int VERSION = 2;
private SQLiteDatabase db;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
}
public Cursor catalog(String s) {
db = getWritableDatabase();
Cursor c;
if (s.equals(""))
c = db.query("catalog", null, null, null, null, null, "_id asc");
else
c = db.query("catalog", null, "lawName LIKE '%" + s + "%'", null, null, null, "_id asc");
return c;
}
}