how should I open and close my database properly

前端 未结 5 1652
挽巷
挽巷 2021-02-06 06:39

I have an app which stores some data in a SQLite DB.Also I\'m doing a lot of query an requery in my app.I have about 15 activities in it.And almoust all use the DB to query for

5条回答
  •  灰色年华
    2021-02-06 07:23

    In my app I open connection to database in myApplication class (your custom class that extends Application - it should be named the same as your application in androidManifest).

    AndroidManifest.xml

    
    

    MyApplication .java

    public class MyApplication extends Application {
    
        private DatabaseAdapter dbAdapter;
    
    
        @Override
        public void onCreate() {
            dbAdapter = new DatabaseAdapter(getApplicationContext());
            dbAdapter.open();
        }
    

    And in each class that need db connection I simply use:

    MyApplication myApplication = (MyApplication) this.getApplication();
    DatabaseAdapter dbAdapter= myApplication.getDatabaseAdapter();
    

    MyApplication is run automatically on every application start. This way I keep only one connection to DB so it's closed when app is being removed from memory without any problem.

提交回复
热议问题