Copy database files on Android

Source: Internet
Author: User

During Android development, sometimes it is not necessary to create a database and then insert data. For example, you need to provide a search function for a large amount of data resources. Such as the number, city list, and IP address. At this time, if the key database is inserted into the database one by one, it will not only take time, occupy resources, but also sometimes import errors. The best way is to build the database, insert the data, and put the beifen. DB file in the raw directory (if not, create one under the res directory. When creating a database, copy the file to the databases Directory: databases_dir = "/data/yourpackagedir/databases ",
Database_name = "beifen. DB ". For details, see the code:

        public static synchronized CityDBHelper getInstance(Context context) {        copyDatabaseFile(context, true);        if(mDatabase == null){            mDatabase =  new CityDBHelper(context);        }        return mDatabase;    }    public static void copyDatabaseFile(Context context, boolean isfored) {Log.v(TAG, "--------------------------------copyDatabaseFile-");File dir = new File(DATABASES_DIR);if (!dir.exists() || isfored) {try {dir.mkdir();} catch (Exception e) {e.printStackTrace();}}File dest = new File(dir, DATABASE_NAME);if(dest.exists() && !isfored){return ;}try {if(dest.exists()){dest.delete();}dest.createNewFile();InputStream in = context.getResources().openRawResource(R.raw.beifen);int size = in.available();byte buf[] = new byte[size];in.read(buf);in.close();FileOutputStream out = new FileOutputStream(dest);out.write(buf);out.close();} catch (Exception e) {e.printStackTrace();}}

If you are not at ease, you can perform a copy check when running the contentprovider query (generally, the copy database is used for query ).

copyDatabaseFile(context, false)

If the file does not exist, copy it. If yes, do not copy it.

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.