在Android中不能直接打开res /raw目录中的数据库文件,而需要在程序第一次启动时将该文件复制到手机内存或SD卡的某个目录中,
然后再打开该数据库文件。
复制的基本方法是使用getResources().openRawResource方法获得res/raw目录中资源的 InputStream对象,
然后将该InputStream对象中的数据写入其他的目录中相应文件中。
在Android SDK中可以使用SQLiteDatabase.openOrCreateDatabase方法来打开任意目录中的SQLite数据库文件。
实现如下:copyDB();
private void copyDB() {
//只要你拷贝了一次,我就不要你再拷贝了
try {
File file = new File(getFilesDir(), "address.db");
if(file.exists()&&file.length()>0){
//正常了,就不需要拷贝了
Log.i("copyDB", "正常了,就不需要拷贝了");
}else{
//().openRawResource
//InputStream is = getAssets().open("address.db");
InputStream is = getResources().openRawResource(R.raw.address);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!= -1){
fos.write(buffer, 0, len);
}
is.close();
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
打开数据库:
public static String path = "data/data/com.itheima.mobilesafe/files/address.db";
public static String SearchNumber(String number){
String adrress = number;
SQLiteDatabase openDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
Cursor cursor = openDatabase.rawQuery("select location from data2 where id=(select outkey from data1 where id=?)",
new String[]{number.substring(0,7)});
while(cursor.moveToNext()){
String location = cursor.getString(0);
adrress = location ;
}
return adrress;
}