我之前要将外部的数据库读进来的做法是:
将db文件放在res的raw路径(可以自己添加这个路径)下面,要打开它的时候这样:
private String filename = DB_PATH+"/"+DB_NAME;
DB_PATH我是这样定义的:
public static final String DB_PATH = "/data"+Environment.getDataDirectory().getAbsolutePath()
+"/"+PACKAGE_NAME;
DB_NAME肯定就是你数据库的名字啦。
public void open()throws SQLException
{
writefromraw(filename);
db = opendatabase();
}
private void writefromraw(String dbfile) {
// TODO Auto-generated method stub
try {
if (!(new File(dbfile).exists())) {
InputStream is = mContext.getResources().openRawResource(
R.raw.livetv_database);
FileOutputStream fos = new FileOutputStream(dbfile);
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
} catch (FileNotFoundException e) {
Log.e("Database", "File not found");
e.printStackTrace();
} catch (IOException e) {
Log.e("Database", "IO exception");
e.printStackTrace();
}
}
把数据库变量改成静态变量,或者用单例模式。
这样应用层就可以用数据库变量,直接判断是否被打开了。