Advertisement
vergepuppeter

DatabaseManager

Oct 16th, 2018
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.05 KB | None | 0 0
  1. /**
  2.  * Created by Developer on 24/08/2016.
  3.  */
  4.  
  5. import android.content.Context;
  6. import android.database.sqlite.SQLiteDatabase;
  7. import android.database.sqlite.SQLiteOpenHelper;
  8.  
  9. import java.util.concurrent.ConcurrentHashMap;
  10. import java.util.concurrent.atomic.AtomicInteger;
  11.  
  12. /** Extend this class and use it as an SQLiteOpenHelper class
  13.  *
  14.  *
  15.  * If distributing: Keep my notes that are self-promoting. Keep or improve the other notes.
  16.  * If distributing (to programmers) in a way that the notes cannot be read, please include a readme file and provide
  17.  * a link to http://androidsqlitelibrary.com
  18.  * You don't have to keep the self-promotion stuff and you don't have to keep the link in a readme, but I would appreciate it.
  19.  * If you ever need help with this code, contact me at support@androidsqlitelibrary.com (or support@jakar.co )
  20.  *
  21.  * Do not sell this. but use it as much as you want. There are no implied or express warranties with this code.
  22.  *
  23.  * This is a simple database manager class which makes threading/synchronization super easy.
  24.  *
  25.  * Extend this class and use it like an SQLiteOpenHelper, but use it as follows:
  26.  *  Instantiate this class once in each thread that uses the database.
  27.  *  Make sure to call {@link #close()} on every opened instance of this class
  28.  *  If it is closed, then call {@link #open()} before using again.
  29.  *
  30.  * Call {@link #open()} to get an instance of the underlying SQLiteDatabse class (which is synchronized).
  31.  *
  32.  *
  33.  * I also implement this system (well, it's very similar) in my <a href="http://androidslitelibrary.com">Android SQLite Libray</a> at http://androidslitelibrary.com
  34.  *
  35.  *
  36.  */
  37. abstract public class DatabaseManager {
  38.  
  39.     /**See SQLiteOpenHelper documentation
  40.      */
  41.     abstract public void onCreate(SQLiteDatabase db);
  42.     /**See SQLiteOpenHelper documentation
  43.      */
  44.     abstract public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
  45.     /**Optional.
  46.      * *
  47.      */
  48.     public void onOpen(SQLiteDatabase db){}
  49.     /**Optional.
  50.      *
  51.      */
  52.     public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
  53.     /**Optional
  54.      *
  55.      */
  56.     public void onConfigure(SQLiteDatabase db){}
  57.  
  58.  
  59.  
  60.     /** The SQLiteOpenHelper class is not actually used by your application.
  61.      *
  62.      */
  63.     static private class DBSQLiteOpenHelper extends SQLiteOpenHelper {
  64.  
  65.         DatabaseManager databaseManager;
  66.         private AtomicInteger counter = new AtomicInteger(0);
  67.  
  68.         public DBSQLiteOpenHelper(Context context, String name, int version, DatabaseManager databaseManager) {
  69.             super(context, name, null, version);
  70.             this.databaseManager = databaseManager;
  71.         }
  72.  
  73.         public void addConnection(){
  74.             counter.incrementAndGet();
  75.         }
  76.         public void removeConnection(){
  77.             counter.decrementAndGet();
  78.         }
  79.         public int getCounter() {
  80.             return counter.get();
  81.         }
  82.         @Override
  83.         public void onCreate(SQLiteDatabase db) {
  84.             databaseManager.onCreate(db);
  85.         }
  86.  
  87.         @Override
  88.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  89.             databaseManager.onUpgrade(db, oldVersion, newVersion);
  90.         }
  91.  
  92.         @Override
  93.         public void onOpen(SQLiteDatabase db) {
  94.             databaseManager.onOpen(db);
  95.         }
  96.  
  97.         @Override
  98.         public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  99.             databaseManager.onDowngrade(db, oldVersion, newVersion);
  100.         }
  101.  
  102.         @Override
  103.         public void onConfigure(SQLiteDatabase db) {
  104.             databaseManager.onConfigure(db);
  105.         }
  106.     }
  107.  
  108.     private static final ConcurrentHashMap<String,DBSQLiteOpenHelper> dbMap = new ConcurrentHashMap<String, DBSQLiteOpenHelper>();
  109.  
  110.     private static final Object lockObject = new Object();
  111.  
  112.  
  113.     private DBSQLiteOpenHelper sqLiteOpenHelper;
  114.     private SQLiteDatabase db;
  115.     private Context context;
  116.     private boolean isActive;
  117.  
  118.     /** Instantiate a new DB Helper.
  119.      * <br> SQLiteOpenHelpers are statically cached so they (and their internally cached SQLiteDatabases) will be reused for concurrency
  120.      *
  121.      * @param context Any {@link android.content.Context} belonging to your package.
  122.      * @param name The database name. This may be anything you like. Adding a file extension is not required and any file extension you would like to use is fine.
  123.      * @param version the database version.
  124.      */
  125.     public DatabaseManager(Context context, String name, int version) {
  126.         String dbPath = context.getApplicationContext().getDatabasePath(name).getAbsolutePath();
  127.         synchronized (lockObject) {
  128.             sqLiteOpenHelper = dbMap.get(dbPath);
  129.             if (sqLiteOpenHelper==null) {
  130.                 sqLiteOpenHelper = new DBSQLiteOpenHelper(context, name, version, this);
  131.                 dbMap.put(dbPath,sqLiteOpenHelper);
  132.             }
  133.             //SQLiteOpenHelper class caches the SQLiteDatabase, so this will be the same SQLiteDatabase object every time
  134.             db = sqLiteOpenHelper.getWritableDatabase();
  135.         }
  136.         this.context = context.getApplicationContext();
  137.         this.isActive = true;
  138.     }
  139.     /** Alias for {@link #open()}, so see that method
  140.      *
  141.      * @deprecated Previously just returned the SQLiteDatabase object. Now just calls (and returns) open()
  142.      */
  143.     @Deprecated
  144.     public SQLiteDatabase getDb(){
  145.         return open();
  146.     }
  147.  
  148.     /** Check if the underlying SQLiteDatabase is open
  149.      *
  150.      * @return whether the DB is open or not (checks for null, to prevent crashing)
  151.      */
  152.     public boolean isOpen(){
  153.         return (db!=null&&db.isOpen());
  154.     }
  155.  
  156.  
  157.     /** Lowers the DB counter by 1 for any {@link DatabaseManager}s referencing the same DB on disk
  158.      *  <br />If the new counter is 0, then the database will be closed.
  159.      *  <br /><br />This needs to be called before application exit.
  160.      *
  161.      * @return true if the underlying {@link android.database.sqlite.SQLiteDatabase} is closed (counter is 0), and false otherwise (counter > 0)
  162.      */
  163.     public boolean close(){
  164.         if (this.isActive){
  165.             sqLiteOpenHelper.removeConnection();
  166.         }
  167.         int count = sqLiteOpenHelper.getCounter();
  168.         if (count==0){
  169.             synchronized (lockObject){
  170.                 if (db.inTransaction())db.endTransaction();
  171.                 if (db.isOpen())db.close();
  172.                 db = null;
  173.             }
  174.         }
  175.         return (count==0);
  176.     }
  177.     /** Increments the internal db counter by one and opens the db if needed.
  178.      *
  179.      *
  180.      * @return db SQLiteDatabase object which is readable and writable
  181.      */
  182.     public SQLiteDatabase open(){
  183.         if (!this.isActive){
  184.             sqLiteOpenHelper.addConnection();
  185.         }
  186.         if (db==null||!db.isOpen()){
  187.             synchronized (lockObject){
  188.                 db = sqLiteOpenHelper.getWritableDatabase();
  189.             }
  190.         }
  191.         this.isActive = true;
  192.         return db;
  193.     }
  194. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement