In the previous contact project, you need to import the existing database contact.db after the app is installed to display the data stored in the database. This is also a face test, so how to achieve it?
When you create a new raw folder in Res, the files in the Res\raw directory are not compressed so that you can directly extract the files in that directory. So how to import the database file contact.db from the raw file into the databases directory in the Android program?
The following is a tool class for importing an existing database: Importdatabase
Public void Importdatabase() {//directory where the database is storedString Dirpath ="/data/data/com.example.contact/databases"; File dir =NewFile (Dirpath);if(!dir.exists ()) {Dir.mkdir (); }//Database filesFile File =NewFile (dir,"Contact.db");Try{if(!file.exists ()) {File.createnewfile (); }//load the database that needs to be importedInputStream is= This. Getapplicationcontext (). Getresources (). Openrawresource (R.raw.contact); FileOutputStream fos =NewFileOutputStream (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, the Importdatabase () method is called in the OnCreate () method of Mainactivity, and the database is created automatically after the application installation is complete.
Using an existing SQLite database in an Android program