Use the existing SQLite database in the Android Program
In the previous contact project, the pre-stored data in the database needs to be displayed after the application is installed. In this case, you need to import the existing database contact. db. This is also an interview question. How can this problem be achieved?
First, create a raw folder in res. Files in the res \ raw directory will not be compressed, so that files in the directory can be extracted directly. So how to import the database file contact. db under the raw file to the database directory in the Android program?
The following provides a tool class for importing existing databases: importDatabase
Public void importDatabase () {// directory where the database is stored String dirPath = "/data/com. example. contact/databases "; File dir = new File (dirPath); if (! Dir. exists () {dir. mkdir () ;}// database File file = new File (dir, "contact. db"); try {if (! File. exists () {file. createNewFile ();} // load the database InputStream to be imported is = this. getApplicationContext (). getResources (). openRawResource (R. raw. contact); FileOutputStream fos = new FileOutputStream (file); byte [] buffere = new byte [is. available ()]; is. read (buffere); fos. write (buffere); is. close (); fos. close ();} catch (FileNotFoundException e) {e. printStackTrace ();} catcriOException e) {e. p'ntstacktrace ();}}
Finally, you can call the importDatabase () method in the oncreate () method of MainActivity. After the application is installed, the database is automatically created.