Use the existing SQLite database in the Android Program

Source: Internet
Author: User

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.

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.