How do I open a database file in the Res/raw directory?

Source: Internet
Author: User
Tags sqlite database

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?

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.