Android uses the SQLite database stored in the Assets folder

Source: Internet
Author: User

Because the project needs to bring the data, so we put the data into a SQLite database file, and then put the file under the Assets folder. From the beginning of the plan to copy the folder from the assets folder to the phone's SD card or the phone's own storage before use, and then consider that each copy is not efficient, and if it involves the modification of the database operation, the data is restored.

So the package is written, the package is just the first time the database file is used to copy the folder to the phone's/data/data/application/database folder, and then directly from this place to use. And it allows you to get the Sqlitedatabase object directly from the database name under the Assets folder, which greatly facilitates your use of the database.

Package Com.jemsn.database;import Java.io.file;import Java.io.fileoutputstream;import java.io.InputStream;import Java.io.outputstream;import Java.util.hashmap;import Java.util.map;import Android.content.context;import Android.content.sharedpreferences;import Android.content.res.assetmanager;import Android.database.sqlite.sqlitedatabase;import android.util.log;/** * This was a Assets database Manager * Use it, you can u Se a assets database file in application * It would copy the database file to "/data/data/[your application package Nam E]/database "When you first time your use it * and you can get a Sqlitedatabase object by the assets database file * @aut Hor Robintang * @time 2012-09-20 * * * * for use: * 1. Initialize Assetsdatabasemanager * 2. Get Assetsdatabasemanager * 3. Get a Sqlitedatabase object through database file * 4. Use the This database object * * Using Example: * Assetsdatabasemanager.initmanager (Getapplication ());//This method was only Need call one time * assetsdataBasemanager mg = Assetsdatabasemanager.getmanager ();//Get a Assetsdatabasemanager object * sqlitedatabase db1 = Mg.getDat Abase ("db1.db");//Get Sqlitedatabase object, Db1.db is a file in assets folder * db1.??? Every operate by your want * of cause, you can use the Assetsdatabasemanager.getmanager (). Getdatabase ("xx") to get a databas e When you need use a database */public class Assetsdatabasemanager {private static String tag = "Assetsdatabase"; Logcatprivate static String DatabasePath = "/data/data/%s/database"; %s is packagename//A mapping from assets database file to Sqlitedatabase objectprivate map<string, SQLITEDATABASE&G T databases = new hashmap<string, sqlitedatabase> ();//context of applicationprivate context context = null;//Singlet On patternprivate static Assetsdatabasemanager minstance = null;/** * Initialize Assetsdatabasemanager * @param context, C Ontext of application */public static void InitManager (context context) {if (minstance = = null) {minstance = nEW Assetsdatabasemanager (context);}} /** * Get a Assetsdatabasemanager object * @return, if success return a Assetsdatabasemanager object, else return null */p Ublic static Assetsdatabasemanager GetManager () {return minstance;} Private Assetsdatabasemanager (Context context) {This.context = context;} /** * Get A assets database, if this was opened this method was only return a copy of the opened database * @param DBFile, the assets file which'll be opened for a database * @return, if success it return a Sqlitedatabase object else r Eturn null */public sqlitedatabase getdatabase (String dbfile) {if (Databases.get (dbfile)! = null) {LOG.I (tag, String.Format ("Return a database copy of%s", DBFile)); return (sqlitedatabase) databases.get (dbfile);} if (context==null) return null; LOG.I (Tag, String.Format ("Create database%s", dbfile)); String spath = Getdatabasefilepath (); String sfile = Getdatabasefile (DBFile); File File = new file (sfile); Sharedpreferences dbs = context.getsharedpreferences (assetsdatAbaseManager.class.toString (), 0); Boolean flag = Dbs.getboolean (DBFile, false); Get Database file flag, if true means this Database file is copied and validif (!flag | |!file.exists ()) {file = new Fil E (spath), if (!file.exists () &&!file.mkdirs ()) {LOG.I (tag, "Create \" "+spath+" \ "fail!"); return null;} if (!copyassetstofilesystem (DBFile, sfile)) {LOG.I (tag, String.Format ("Copy%s to%s fail!", DBFile, Sfile)); return null;} Dbs.edit (). Putboolean (DBFile, True). commit ();} Sqlitedatabase db = Sqlitedatabase.opendatabase (sfile, NULL, sqlitedatabase.no_localized_collators), if (db! = null) { Databases.put (dbfile, db);} return DB;} Private String Getdatabasefilepath () {return String.Format (DatabasePath, Context.getapplicationinfo (). PackageName);} private string Getdatabasefile (string dbfile) {return Getdatabasefilepath () + "/" +dbfile;} Private Boolean Copyassetstofilesystem (String assetssrc, String des) {LOG.I (tag, "Copy" +assetssrc+ "to" +des); Nputstream istream = Null;outputstream Ostream = null;try{Assetmanager am = context.getassets (); istream = Am.open (ASSETSSRC); ostream = new FileOutputStream (DES); byte[] buffer = NE    W byte[1024];    int length;    while (length = istream.read (buffer)) >0) {ostream.write (buffer, 0, length);    } istream.close (); Ostream.close ();} catch (Exception e) {e.printstacktrace (); Try{if (Istream!=null) istream.close (); if (ostream!=null) Ostream.close ();} catch (Exception ee) {ee.printstacktrace ();} return false;} return true;} /** * Close Assets Database * @param dbfile, the assets file which would be closed soon * @return, the status of this opera Ting */public boolean closeDatabase (String dbfile) {if (Databases.get (dbfile)! = null) {Sqlitedatabase db = ( Sqlitedatabase) Databases.get (dbfile);d b.close ();d atabases.remove (DBFile); return true;} return false;} /** * Close All assets database */static public void Closealldatabase () {LOG.I (tag, "closealldatabase"); if (minstance! = nul L) {for (int i=0; i<minstance.databases.size (); ++i) {if (MInstance.databases.get (i) {!=null) {mInstance.databases.get (i). Close ();}} MInstance.databases.clear ();}}}
The process used is also very simple, the application started when the initialization, and then can be anywhere to get the manager in the Assets folder under the database file name directly get the Sqlitedatabase object, then the operation of the database is completely you ...

Simple examples of use:

Initialize, you only need to call once Assetsdatabasemanager.initmanager (Getapplication ());//Get Management objects, Because the database needs to be managed object to be able to get assetsdatabasemanager mg = Assetsdatabasemanager.getmanager ();//Get the database Sqlitedatabase through the management object DB1 = Mg.getdatabase ("db1.db");//operation of the database Db1.execsql ("INSERT into TB ([id],[content]) VALUES (null, ' db1 ');");
It is important to note that when you get a database object, you distinguish the case of the database file name.


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.