Article source: blog.csdn.net/trbbadboy/a…

Since the project required built-in data, we put the data into an SQLite database file, which we then placed under assets. At first, I planned to copy the folder from the assets folder to the SD card of the mobile phone or the storage of the mobile phone every time and then use it. Later, I considered that it would be inefficient to copy the folder every time and the data would be restored if the modification of the database was involved.

The wrapper simply copies the folder to the /data/data/ application registration /database folder on the phone the first time you use the database file, and then uses it directly from there. It also allows you to retrieve an SQLiteDatabase object directly from the database name in assets, making it much easier to use the database.

Encapsulation is as follows:

[java]  view plain copy print ?

  1. package com.sin.android.database;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.util.HashMap;  
  8. import java.util.Map;  
  9.   
  10. import android.content.Context;  
  11. import android.content.SharedPreferences;  
  12. import android.content.res.AssetManager;  
  13. import android.database.sqlite.SQLiteDatabase;  
  14. import android.util.Log;  
  15.   
  16. / * *
  17.  * This is a Assets Database Manager 
  18.  * Use it, you can use a assets database file in you application 
  19.  * It will copy the database file to “/data/data/[your application package name]/database” when you first time you use it 
  20.  * Then you can get a SQLiteDatabase object by the assets database file  
  21.  * @author RobinTang 
  22.  * @time 2012-09-20 
  23.  *  
  24.  *  
  25.  * How to use: 
  26.  * 1. Initialize AssetsDatabaseManager 
  27.  * 2. Get AssetsDatabaseManager 
  28.  * 3. Get a SQLiteDatabase object through database file 
  29.  * 4. Use this database object 
  30.  *  
  31.  * Using example: 
  32.  * AssetsDatabaseManager.initManager(getApplication()); // this method is only need call one time 
  33.  * AssetsDatabaseManager mg = AssetsDatabaseManager.getManager();   // get a AssetsDatabaseManager object 
  34.  * SQLiteDatabase db1 = mg.getDatabase(“db1.db”);   // get SQLiteDatabase object, db1.db is a file in assets folder 
  35.  * db1.???  // every operate by you want 
  36.  * Of cause, you can use AssetsDatabaseManager.getManager().getDatabase(“xx”) to get a database when you need use a database 
  37. * /
  38. public class AssetsDatabaseManager {  
  39.     private static String tag = “AssetsDatabase”; // for LogCat  
  40.     private static String databasepath = “/data/data/%s/database”; // %s is packageName  
  41.       
  42.       
  43.     // A mapping from assets database file to SQLiteDatabase object  
  44.     private Map<String, SQLiteDatabase> databases = new HashMap<String, SQLiteDatabase>();  
  45.       
  46.     // Context of application  
  47.     private Context context = null;  
  48.       
  49.     // Singleton Pattern  
  50.     private static AssetsDatabaseManager mInstance = null;  
  51.       
  52. / * *
  53.      * Initialize AssetsDatabaseManager 
  54.      * @param context, context of application 
  55. * /
  56.     public static void initManager(Context context){  
  57.         if(mInstance == null){  
  58.             mInstance = new AssetsDatabaseManager(context);  
  59.         }  
  60.     }  
  61.       
  62. / * *
  63.      * Get a AssetsDatabaseManager object 
  64.      * @return, if success return a AssetsDatabaseManager object, else return null 
  65. * /
  66.     public static AssetsDatabaseManager getManager(){  
  67.         return mInstance;  
  68.     }  
  69.       
  70.     private AssetsDatabaseManager(Context context){  
  71.         this.context = context;  
  72.     }  
  73.       
  74. / * *
  75.      * Get a assets database, if this database is opened this method is only return a copy of the opened database 
  76.      * @param dbfile, the assets file which will be opened for a database 
  77.      * @return, if success it return a SQLiteDatabase object else return null 
  78. * /
  79.     public SQLiteDatabase getDatabase(String dbfile) {  
  80. if(databases.get(dbfile) ! = null){
  81.             Log.i(tag, String.format(“Return a database copy of %s”, dbfile));  
  82.             return (SQLiteDatabase) databases.get(dbfile);  
  83.         }  
  84.         if(context==null)  
  85.             return null;  
  86.           
  87.         Log.i(tag, String.format(“Create database %s”, dbfile));  
  88.         String spath = getDatabaseFilepath();  
  89.         String sfile = getDatabaseFile(dbfile);  
  90.           
  91.         File file = new File(sfile);  
  92.         SharedPreferences dbs = context.getSharedPreferences(AssetsDatabaseManager.class.toString(), 0);  
  93.         boolean flag = dbs.getBoolean(dbfile, false); // Get Database file flag, if true means this database file was copied and valid  
  94. if(! flag || ! file.exists()){
  95.             file = new File(spath);  
  96. if(! file.exists() && ! file.mkdirs()){
  97. Log.i(tag, “Create \””+spath+”\” fail!” );
  98.                 return null;  
  99.             }  
  100. if(! copyAssetsToFilesystem(dbfile, sfile)){
  101. Log.i(tag, String.format(“Copy %s to %s fail!” , dbfile, sfile));
  102.                 return null;  
  103.             }  
  104.               
  105.             dbs.edit().putBoolean(dbfile, true).commit();  
  106.         }  
  107.           
  108.         SQLiteDatabase db = SQLiteDatabase.openDatabase(sfile, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);  
  109. if(db ! = null){
  110.             databases.put(dbfile, db);  
  111.         }  
  112.         return db;  
  113.     }  
  114.       
  115.     private String getDatabaseFilepath(){  
  116.         return String.format(databasepath, context.getApplicationInfo().packageName);  
  117.     }  
  118.       
  119.     private String getDatabaseFile(String dbfile){  
  120.         return getDatabaseFilepath()+”/”+dbfile;  
  121.     }  
  122.       
  123.     private boolean copyAssetsToFilesystem(String assetsSrc, String des){  
  124.         Log.i(tag, “Copy “+assetsSrc+” to “+des);  
  125.         InputStream istream = null;  
  126.         OutputStream ostream = null;  
  127.         try{  
  128.             AssetManager am = context.getAssets();  
  129.             istream = am.open(assetsSrc);  
  130.             ostream = new FileOutputStream(des);  
  131.             byte[] buffer = new byte[1024];  
  132.             int length;  
  133.             while ((length = istream.read(buffer))>0){  
  134.                 ostream.write(buffer, 0, length);  
  135.             }  
  136.             istream.close();  
  137.             ostream.close();  
  138.         }  
  139.         catch(Exception e){  
  140.             e.printStackTrace();  
  141.             try{  
  142. if(istream! =null)
  143.                     istream.close();  
  144. if(ostream! =null)
  145.                     ostream.close();  
  146.             }  
  147.             catch(Exception ee){  
  148.                 ee.printStackTrace();  
  149.             }  
  150.             return false;  
  151.         }  
  152.         return true;  
  153.     }  
  154.       
  155. / * *
  156.      * Close assets database 
  157.      * @param dbfile, the assets file which will be closed soon 
  158.      * @return, the status of this operating 
  159. * /
  160.     public boolean closeDatabase(String dbfile){  
  161. if(databases.get(dbfile) ! = null){
  162.             SQLiteDatabase db = (SQLiteDatabase) databases.get(dbfile);  
  163.             db.close();  
  164.             databases.remove(dbfile);  
  165.             return true;  
  166.         }  
  167.         return false;  
  168.     }  
  169.       
  170. / * *
  171.      * Close all assets database 
  172. * /
  173.     static public void closeAllDatabase(){  
  174.         Log.i(tag, “closeAllDatabase”);  
  175. if(mInstance ! = null){
  176.             for(int i=0; i<mInstance.databases.size(); ++i){  
  177. if(mInstance.databases.get(i)! =null){
  178.                     mInstance.databases.get(i).close();  
  179.                 }  
  180.             }  
  181.             mInstance.databases.clear();  
  182.         }  
  183.     }  
  184. }  

SQLiteDatabase can be obtained from the database file name in assets folder. After that, the operation of the database is completely up to you…

Simple usage examples:

[java]  view plain copy print ?

  1. // Init, only need to be called once
  2. AssetsDatabaseManager.initManager(getApplication());  
  3. // Get the managed object, because the database needs to get the managed object
  4. AssetsDatabaseManager mg = AssetsDatabaseManager.getManager();  
  5. // Obtain the database from the managed object
  6. SQLiteDatabase db1 = mg.getDatabase(“db1.db”);  
  7. // Perform operations on the database
  8. db1.execSQL(“insert into tb([ID],[content]) values(null, ‘db1’);” );

It is important to note that retrieving database objects is case-sensitive to database file names. \