You cannot open a database file in the Res/raw directory directly in Android, but you need to copy the file to a directory on your phone's memory or SD card The first time the program starts.
Then open the database file.
The basic method of replication is to use the Getresources (). Openrawresource method to obtain the InputStream object for a resource in the Res/raw directory.
The data in the InputStream object is then written to the corresponding file in the other directory.
The Sqlitedatabase.openorcreatedatabase method can be used in the Android SDK to open SQLite database files in any directory.
The implementation is as follows: Copydb ();
private void Copydb () {///If you copy it once, I don't want you to copy the try {File file = new file (Getfilesdir (), "address.db"); if (File.exists () & &file.length () >0) {//normal, no need to copy the LOG.I ("Copydb", "normal, do not need to copy");} 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 Blocke.printstacktrace ();}}
Open the database:
public static string path = "Data/data/com.itheima.mobilesafe/files/address.db";p ublic 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;}
How do I open a database file in the Res/raw directory?