How to initialize sqlite database once from a helper class in Android

前端 未结 2 841
半阙折子戏
半阙折子戏 2020-12-04 00:24

I have a custom DataBaseHelper class which extends SQLiteOpenHelper,which looks like this :

package com.stampii.stampii.comm.rpc;


import java.io.File;
impo         


        
相关标签:
2条回答
  • 2020-12-04 01:08

    Create your instance only once like this, The same code you can add in DB handler class but I prefer to keep it seperate.

    public class MyTestDatabaseInstanceHolder {
    
        public MyTestDBHandler DBHelper;  
        public static SQLiteDatabase m_ObjDataBase; // This is global variable to access across the applicaiton
    
        public static void createDBInstance(Context pContext){
            if(DBHelper == null) {
                DBHelper = new WLDBHandler(pContext); // This will be your DB Handler Class
                m_cObjDataBase = DBHelper.openAndCreateDataBase(); // Initialze the DB Note: openAndCreateDataBase is a utility method created by you to do everything an return the DB object
            }
          }
    }
    

    In your entry point (Splash Screen) call this:

    MyTestDatabaseInstanceHolder.createDBInstance(getApplicationContext());
    

    Usage - Some other Class:

    MyTestDatabaseInstanceHolder.m_ObjDataBase.rawQuery(---);
    
    0 讨论(0)
  • 2020-12-04 01:08

    I think for initializing your Database you have to pass the context of the activity in which you are using it, so for used it in every activity you have to initialize in every activity. If I m wrong please let me know.

    0 讨论(0)
提交回复
热议问题