How to import an external database file larger than 1 MB for Android

Source: Internet
Author: User
Tags name database
Import  Java. Io. file;  Import  Java. Io. fileoutputstream;  Import  Java. Io. ioexception;  Import  Java. Io. inputstream;  Import  Java. Io. outputstream;  Import  Android. content. context;  Import  Android. database. SQLite. sqlitedatabase;  Import Android. database. SQLite. sqlitedatabase. cursorfactory;  Import  Android. database. SQLite. sqliteexception;  Import  Android. database. SQLite. sqliteopenhelper;  /**  * Database files under assets will be copied directly to db_path, but the database file size is limited to less than 1 MB * if there are large files larger than 1 MB, you must first split them into N small files, replace copydatabase () with copybigdatabase ()  */  Public   Class Dbmanager Extends  Sqliteopenhelper {  // Version of the user database file      Private   Static   Final   Int Db_version = 1 ;  //  The storage path of the database file is the default location. com. Rys. lb is your package name.      Private   Static String db_path = "/data/COM. chishacai /" ;  //  If you want to store database files on the SD card  // Private Static string db_path =  //  Android. OS. environment. getexternalstoragedirectory (). getabsolutepath ()  //  + "/Arthur urcn/drivertest/packfiles /";      Private   Static String db_name = "cscpb. DB" ;  Private   Static String assets_name = "cscdb/cscpb. DB" ;  Private  Sqlitedatabase mydatabase; Private   Final  Context mycontext;  /**  * If the database file is large, use filesplit to split it into small files smaller than 1 MB. In this example, split it into data. db.100 data. db.101 * Data. db.102 ....  */      //  Suffix of the first file name      Private   Static   Final   Int Assets_suffix_begin = 0 ;  //  Suffix of the last file name     Private   Static   Final   Int Assets_suffix_end = 3 ;  Private   Static  Sqlitedatabase credb;  /**  * This constructor must be included in the subclass of sqliteopenhelper *  @ Param  Context context object *  @ Param  Name database name *  @ Param Factory is generally null *  @ Param  Version: the version of the current database. The value must be an integer and increase progressively.  */      Public  Dbmanager (context, string name, cursorfactory factory,  Int  Version ){  //  The constructor in the parent class must be called through super.          Super (Context, name, Null  , Version );  This . Mycontext =Context ;}  Public Dbmanager (context, string name, Int  Version ){  This (Context, name, Null  , Version );}  Public  Dbmanager (context, string name ){  This  (Context, name, db_version );}  Public  Dbmanager (context ){ This (Context, db_path + Db_name );}  Public   Void Createdatabase () Throws  Ioexception {  Boolean Dbexist = Checkdatabase ();  If  (Dbexist ){  //  The database already exists. Do nothing.  System. Out. println ( "The database already exists");}  Else  {  //  Create a database              Try  {File dir = New  File (db_path );  If (! Dir. exists () {dir. mkdirs ();} file DBF = New File (db_path + Db_name ); If  (DBF. exists () {DBF. Delete ();} credb = Sqlitedatabase. openorcreatedatabase (DBF, Null  );  //  Copy the DB file in asseets to db_path.  //  Copydatabase ();  Copybigdatabase ();}  Catch  (Ioexception e ){  Throw   New Error ("database creation failed" );}}}  //  Check whether the database is valid      Private   Boolean  Checkdatabase () {sqlitedatabase checkdb = Null  ; String mypath = Db_path + Db_name;  Try  {Checkdb = Sqlitedatabase. opendatabase (mypath, Null , Sqlitedatabase. open_readonly );}  Catch  (Sqliteexception e ){  //  Database does't exist yet.  }  If (Checkdb! = Null  ) {Checkdb. Close (); system. Out. println ( "Close" );}  Return Checkdb! = Null ? True : False  ;}  Public  Dbmanager open1 () {string mypath = Db_path + Db_name; system. Out. println ( "The database has ..." ); Mydatabase = Sqlitedatabase. opendatabase (mypath, Null  , Sqlitedatabase. open_readonly); system. Out. println ( "Open Database" );  Return   This  ;} /**  * Copies your database from your local assets-folder to the just created * empty database in the system folder, from where it can be accessed and * handled. This is done by transfering bytestream .*  */      Private   Void Copydatabase () Throws  Ioexception {  //  Open your local dB as the input stream Inputstream myinput = Mycontext. getassets (). Open (assets_name );  // Path to the just created empty DB String outfilename = db_path + Db_name;  //  Open the empty dB as the output stream Outputstream myoutput = New  Fileoutputstream (outfilename );  //  Transfer bytes from the inputfile to the outputfile          Byte [] Buffer = New   Byte [1024 ]; Int  Length;  While (Length = myinput. Read (buffer)> 0 ) {Myoutput. Write (buffer, 0 , Length );}  //  Close the streams  Myoutput. Flush (); myoutput. Close (); myinput. Close ();}  //  This is used when copying large database files under assets.      Private   Void Copybigdatabase () Throws Ioexception {inputstream myinput; string outfilename = Db_path + Db_name; outputstream myoutput = New  Fileoutputstream (outfilename );  For ( Int I = assets_suffix_begin; I <assets_suffix_end + 1; I ++ ) {Myinput = Mycontext. getassets (). Open (assets_name + "." + I );  Byte [] Buffer = New   Byte [1024 ];  Int  Length;  While (Length = myinput. Read (buffer)> 0 ) {Myoutput. Write (buffer, 0 , Length) ;}myoutput. Flush (); myinput. Close () ;}myoutput. Close (); system. Out. println ( "The database has been copied" );}  /**  * Shut down the newly created database.  */      Public   Void Closedb (){  If (Credb! = Null  ) {Credb. Close (); system. Out. println ( "The created database has been disabled" ) ;}}@ Override  Public   Synchronized   Void  Close (){  If (Mydatabase! = Null  ) {Mydatabase. Close (); system. Out. println ( "Disabled successfully 1");}  Super  . Close (); system. Out. println ( "Disabled successfully 2" );}  /**  * This function is executed when it is created for the first time. In fact, this method is called only when the sqlitedatabase object is obtained for the first time.  */  @ Override  Public   Void  Oncreate (sqlitedatabase dB ){}  /**  * Used when the database table structure changes  */ @ Override  Public   Void Onupgrade (sqlitedatabase dB, Int Oldversion, Int  Newversion ){}  Public   Void  Open () {sqlitedatabase = This . Openorcreatedatabase ("data. DB" ,  Null  );}  Private Sqlitedatabase openorcreatedatabase (string, object ){  //  Todo auto-generated method stub          Return   Null  ;}} 

 

Something changed,CodeCan be understood.

1. If the database file is larger than 1 MB, use the filesplit tool to cut. Download this software tool first 2. First, put the existing database under the assets folder. If this file does not exist, create this folder in the android project.
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.