Read database + database version update
Attention:
A, place the database with the APK released under the/res/raw path under Android engineering.
b, when the database file is stored on the phone, the path is/data/data/your package name/databases, and the other path will go wrong.
Sqliteopenhelper is inherited when you need to create a new database directly in the project, but this article is about publishing the database with the APK, so there's no need to inherit Sqliteopenhelper, But also need to do a layer of test.db packaging, in the Test.db wrapper class to operate the database.
The process of writing a program often changes the structure of the database, you can use the database version number to determine whether the database on the phone should be updated, SQLite database user_version provides this help. The following command can change the user_version,user_version of the database must be of integer type.
PRAGMA [Database.] User_version = 2;
Here is the implementation code, which includes writing the database to the phone and updating the database.
1 Public classtestsqldatabase{2 3 Private Static FinalString Database_path = "/data/data/your.package.name/databases";4 5 Private Static Final intdatabase_version = 0;6 7 Private Static FinalString database_name = "Test.db";8 9 Private StaticString outfilename = Database_path + "/" +database_name;Ten One Privatecontext context; A - Privatesqlitedatabase database; - the PublicTestsqldatabase (Context context) { - This. Context =context; - -File File =NewFile (outfilename); + if(File.exists ()) { -Database = Sqlitedatabase.openorcreatedatabase (Outfilename,NULL); + if(Database.getversion ()! =database_version) { A database.close (); at File.delete (); - } - } - Try { - builddatabase (); -}Catch(Exception e) { in e.printstacktrace (); - } to + } - the Private voidBuilddatabase ()throwsexception{ *InputStream myinput =context.getresources (). Openrawresource (r.raw.test); $File File =NewFile (outfilename);Panax Notoginseng -File dir =NewFile (database_path); the if(!dir.exists ()) { + if(!Dir.mkdir ()) { A Throw NewException ("Create failed"); the } + } - $ if(!file.exists ()) { $ Try { -OutputStream Myoutput =NewFileOutputStream (outfilename); - the byte[] buffer =New byte[1024]; - intlength;Wuyi while(length = myinput.read (buffer)) >0){ theMyoutput.write (buffer, 0, length); - } Wu myoutput.close (); - myinput.close (); About}Catch(Exception e) { $ e.printstacktrace (); - } - - } A } +}
Android Database (publish database with APK)