How to Open/Close SQLite db in Android Properly

后端 未结 3 1597
礼貌的吻别
礼貌的吻别 2020-12-15 10:53

I have an app that functions properly and does not force close or crash. But when I look at LogCat, it occasionally gives me this:

05-20 15:24:55.338: E/SQL         


        
3条回答
  •  旧巷少年郎
    2020-12-15 11:13

    I used to do the way @Shikima mentioned above but in complex applications which has many background services, multi-threading,etc it can get real tiresome when you have to manage many database instances and on top of that, opening and closing them.

    To overcome this, I used the following method and it seems to be working fine.

    1.

    Declare and initialize an instance of YourDBHelperClass in your Application base class like this :

    public class App extends Application {
      public static YourDBHelperClass db;
    
      @Override
      public void onCreate() {
        super.onCreate();
        db = new YourDBHelperClass(getApplicationContext());
        db.open();
    
      }
    }
    

    2.

    In you activity, or any other place you want to use the DB, initialize the YourDBHelperClass object like this :

    YourDBHelperClass db = App.db;
    

    And then you can use the database anyway you want without having to worry about opening and closing it manually each time. The SQLiteOpenHelper takes care of the closing when the Application is destroyed

提交回复
热议问题