Using an existing SQLite database in an Android program

Source: Internet
Author: User
Tags sqlite database

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.